Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
0b2b78c
start: proof of work captcha feature.
crhallberg Jul 21, 2025
b3b6c80
feat: session id used to generate consistent secrets.
crhallberg Jul 22, 2025
6fc0381
fix: alignment of captcha with comment.
crhallberg Jul 22, 2025
356676b
fix: send less information back with form, since we have a better sta…
crhallberg Jul 22, 2025
35a4318
doc: copyright 2
crhallberg Jul 22, 2025
5a6f033
chore: qa-js-and-scss
crhallberg Jul 22, 2025
843c2ea
chore: php-cs-fixer
crhallberg Jul 22, 2025
a21c1e2
doc: rename CAPTCHA
crhallberg Jul 22, 2025
1d3336e
Update module/VuFind/src/VuFind/Captcha/PoW.php
crhallberg Jul 22, 2025
5746da2
doc: update copyright
crhallberg Jul 22, 2025
136e3cb
doc: copyright
crhallberg Jul 22, 2025
04fe429
feat: add Altcha as an option.
crhallberg Jul 28, 2025
6b5884f
fix: woke up in the middle of the night in a cold sweat with the abso…
crhallberg Jul 28, 2025
8ff7271
refactor: pass Altcha instance from Factory.
crhallberg Jul 31, 2025
761e780
rm: unused file since vendor supplies WebComponent.
crhallberg Jul 31, 2025
c97bfba
fix: remove postinstall.
crhallberg Jul 31, 2025
8dc7d17
doc: add Altcha LICENSE.
crhallberg Jul 31, 2025
62ca158
remove home-grown pow solution.
crhallberg Aug 6, 2025
d06cb50
fix: escape challenge JSON.
crhallberg Aug 6, 2025
7f1b88a
Update config/vufind/config.ini
crhallberg Aug 6, 2025
182f5bd
docs: fix parameter types.
crhallberg Aug 6, 2025
a9f9003
style: phpcs
crhallberg Aug 6, 2025
a358335
Merge branch 'pow-captcha' of https://github.com/crhallberg/vufind in…
crhallberg Aug 6, 2025
d6972fa
Merge branch 'dev' into pow-captcha
crhallberg Sep 9, 2025
fb11bf4
Merge branch 'dev' into pow-captcha
demiankatz Dec 4, 2025
de5dae0
Fix outdated license text.
demiankatz Dec 4, 2025
826c5a9
Handle garbled input data more robustly.
demiankatz Dec 4, 2025
2e485c6
php-cs-fixer
demiankatz Dec 4, 2025
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
7 changes: 7 additions & 0 deletions config/vufind/config.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2512,6 +2512,7 @@ validateHierarchySequences = true
; - image (generate a local image for the user to interpret)
; - interval (allow an action after a specified time has elapsed from session start
; or previous action)
; - pow (proof of work bot deterent)
; - recaptcha (use Google's ReCaptcha service)
; If multiple values are given, the user will be able to pick their favorite.
; See below for additional type-specific settings.
Expand Down Expand Up @@ -2542,6 +2543,12 @@ validateHierarchySequences = true
; action_interval):
;time_from_session_start = 0

; Proof of Work options
; PHP and JS both natively support sha1, sha256, sha384, sha512.
;pow_hash = sha256
; number of leading zeroes required; default: 5
;pow_difficulty = 5

; See http://www.google.com/recaptcha for more information on reCAPTCHA and to
; create keys for your domain. Make sure that SSL settings are correct in the
; [Http] section, or your Captcha may not work.
Expand Down
5 changes: 4 additions & 1 deletion config/vufind/contentsecuritypolicy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ script-src[] = "https:"
connect-src[] = "'self'"
; If you are using Google Analytics, uncomment the line below
;connect-src[] = "https://*.google-analytics.com"
; worker-src required for jsTree with browsers that don't support 'strict-dynamic' (e.g. Safari):
; worker-src (permission to load web worker JS files)
; (blob) required for jsTree with browsers that don't support 'strict-dynamic' (e.g. Safari):
worker-src[] = "blob:"
; (self) required for proof of work (PoW) Captcha web wworker
worker-src[] = "'self'"
style-src[] = "'self'"
style-src[] = "'unsafe-inline'"
img-src[] = "'self'"
Expand Down
2 changes: 2 additions & 0 deletions module/VuFind/src/VuFind/Captcha/PluginManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class PluginManager extends \VuFind\ServiceManager\AbstractPluginManager
'dumb' => Dumb::class,
'image' => Image::class,
'interval' => Interval::class,
'pow' => PoW::class,
'recaptcha' => ReCaptcha::class,
];

Expand All @@ -65,6 +66,7 @@ class PluginManager extends \VuFind\ServiceManager\AbstractPluginManager
Dumb::class => DumbFactory::class,
Image::class => ImageFactory::class,
Interval::class => IntervalFactory::class,
PoW::class => PoWFactory::class,
ReCaptcha::class => ReCaptchaFactory::class,
];

Expand Down
148 changes: 148 additions & 0 deletions module/VuFind/src/VuFind/Captcha/PoW.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
<?php

/**
* Proof of Work CAPTCHA.
*
* PHP version 8
*
* Copyright (C) Villanova University 2025.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package CAPTCHA
* @author Chris Hallberg <challber@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/

namespace VuFind\Captcha;

use Laminas\Mvc\Controller\Plugin\Params;
use Laminas\Session\ManagerInterface;

use function intval;

/**
* Proof of Work CAPTCHA.
*
* @category VuFind
* @package CAPTCHA
* @author Chris Hallberg <challber@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
class PoW extends AbstractBase
{
/**
* Constructor
*
* @param string $hashAlgo Hash algorithm (default sha256)
* @param int $difficulty Number of leading zeroes needed for proof (default 5)
* @param ManagerInterface $session Session manager
*/
public function __construct(
protected string $hashAlgo,
protected int $difficulty,
protected ManagerInterface $session,
) {
}

/**
* Get list of URLs with JS dependencies to load for the active CAPTCHA type.
*
* @return array
*/
public function getJsIncludes(): array
{
return ['captcha-pow.js'];
}

/**
* Pull the captcha field from controller params and check them for accuracy
* We pull from the form in case config changed since challenge was sent
*
* @param Params $params Controller params
*
* @return bool
*/
public function verify(Params $params): bool
{
$nonce = intval($params->fromPost('pow-captcha-nonce'));
$start = intval($params->fromPost('pow-captcha-start', 0));

// Verify nonce search began with start
if ($nonce < $start) {
error_log(
'PoW: nonce (' . $nonce . ') not incremental from start (' . $start . ')'
);
return false;
}

// Verify work
$challenge = $this->getChallenge($start);
$hashAlgo = $params->fromPost('pow-captcha-hash-algo');
$hash = hash($hashAlgo, $challenge . $nonce);
if (substr($hash, 0, $this->difficulty) !== str_repeat('0', $this->difficulty)) {
error_log(
'PoW: nonce (' . $nonce . ') produces invalid hash (' . $hash . ')'
);
return false;
}

return true;
}

/**
* Generate challenge string from session id
*
* @param int $salt Number to add to session id (we use start number)
*
* @return string
*/
public function getChallenge($salt)
{
return hash('sha256', $this->session->getId() . $salt);
}

/**
* Get difficulty from config
*
* @return int
*/
public function getDifficulty()
{
return $this->difficulty;
}

/**
* Get difficulty from config
*
* @return string
*/
public function getHashAlgo()
{
return $this->hashAlgo;
}

/**
* Get random starting point to prevent repeatable work
*
* @return int
*/
public function getStart()
{
return random_int(1000, 9999);
}
}
90 changes: 90 additions & 0 deletions module/VuFind/src/VuFind/Captcha/PoWFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

/**
* Factory for Proof of Work CAPTCHA module.
*
* PHP version 8
*
* Copyright (C) Villanova University 2025.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package CAPTCHA
* @author Chris Hallberg <challber@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/

namespace VuFind\Captcha;

use Laminas\ServiceManager\Exception\ServiceNotCreatedException;
use Laminas\ServiceManager\Exception\ServiceNotFoundException;
use Laminas\ServiceManager\Factory\FactoryInterface;
use Psr\Container\ContainerExceptionInterface as ContainerException;
use Psr\Container\ContainerInterface;

use function in_array;
use function intval;

/**
* Proof of Work CAPTCHA factory.
*
* @category VuFind
* @package CAPTCHA
* @author Chris Hallberg <challber@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
class PoWFactory implements FactoryInterface
{
/**
* Create an object
*
* @param ContainerInterface $container Service manager
* @param string $requestedName Service being created
* @param null|array $options Extra options (optional)
*
* @return object
*
* @throws ServiceNotFoundException if unable to resolve the service.
* @throws ServiceNotCreatedException if an exception is raised when
* creating a service.
* @throws ContainerException&\Throwable if any other error occurs
*/
public function __invoke(
ContainerInterface $container,
$requestedName,
?array $options = null
) {
if (!empty($options)) {
throw new \Exception('Unexpected options passed to factory.');
}

$config = $container
->get(\VuFind\Config\PluginManager::class)
->get('config');

$hashAlgo = $config->Captcha->hashAlgo ?? 'sha256';
if (!in_array($hashAlgo, hash_algos())) {
throw new \Exception('Invalid hash algorithm: ' . $hashAlgo . '.');
}

return new $requestedName(
$hashAlgo,
intval($config->Captcha->pow_difficulty ?? 5),
$container->get(\Laminas\Session\SessionManager::class),
);
}
}
1 change: 1 addition & 0 deletions module/VuFind/src/VuFind/Controller/Plugin/Captcha.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ public function verify(): bool
$errorMessage = $captcha->getErrorMessage();
}
} catch (\Exception $e) {
error_log($e);
$captchaPassed = false;
$errorMessage = $this->translate('captcha_technical_difficulties');
}
Expand Down
2 changes: 1 addition & 1 deletion themes/bootstrap5/templates/Helpers/captcha.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<?php if (count($this->captchas) == 1):?>
<?php if ($captchaHtml = $this->captcha()->getHtmlForCaptcha($this->captchas[0])): ?>
<label class="form-label"><?=$this->transEsc('captcha_label_single')?></label>
<p><?=$captchaHtml?></p>
<div><?=$captchaHtml?></div>
<?php endif; ?>
<?php else:?>
<label class="form-label"><?=$this->transEsc('captcha_label_multiple')?></label>
Expand Down
2 changes: 1 addition & 1 deletion themes/bootstrap5/templates/RecordTab/usercomments.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
<?=$this->component('star-rating', ['ratingData' => $ratingData, 'allowClear' => 0 === $ratingData['count'] || $this->accountCapabilities()->isRatingRemovalAllowed()]);?>
</div>
<?php endif; ?>
<div class="clearfix"></div>
<?php if ($this->tab->isCaptchaActive()): ?>
<?=$this->captcha()->html(true, false) ?>
<?php endif; ?>
<div class="clearfix"></div>
<input class="btn btn-primary" type="submit" value="<?=$this->transEscAttr('Add your comment')?>">
<div class="loading-spinner js-loading-spinner hidden"><?=$this->icon('spinner') ?> <?=$this->translate('loading_ellipsis')?></div>
</div>
Expand Down
72 changes: 72 additions & 0 deletions themes/root/js/captcha-pow-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* @param {string} algo PHP hash algorithm key
* @returns {string} JS Crypto algorithm key
*/
function phpAlgoToJS(algo) {
const map = {
"sha1": "SHA-1",
"sha256": "SHA-256",
"sha384": "SHA-384",
"sha512": "SHA-512",
};
return algo in map ? map[algo] : algo;
}

/**
* @param {string} hashAlgo SHA family algorithm (for now)
* @param {string} challenge Hash from server
* @param {number} nonce Incrementing number for concat
* @returns {Promise<string>} Hash of challenge + nonce
*/
function hashChallenge(hashAlgo, challenge, nonce) {
return new Promise((resolve, reject) => {
let buffer = new TextEncoder().encode(`${challenge}${nonce}`);
crypto.subtle.digest(phpAlgoToJS(hashAlgo), buffer.buffer).then((result) => {
// convert buffer to byte array
const bytes = Array.from(new Uint8Array(result));

// convert bytes to hex string
const hex = bytes
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");

resolve(hex);
}, reject);
});
}

/**
* @param {MessageEvent} event Contains hash work parameters
* @returns {void} Returns via postMessage
*/
function powWorkerMessage(event) {
const { challenge, difficulty, hashAlgo, start } = event.data;
const algo = phpAlgoToJS(hashAlgo);

const startTime = Date.now();
const target = "0".repeat(difficulty);

/**
* Recursive on Promise resolution
* @param {number} nonce Incrementing number for hash concatenation
* @returns {void}
*/
function attemptHash(nonce) {
hashChallenge(algo, challenge, nonce).then((result) => {
if (result.startsWith(target)) {
// Return to main thread
self.postMessage({
nonce,
iters: nonce - start,
ms: Date.now() - startTime,
});
} else {
attemptHash(nonce + 1);
}
});
}

attemptHash(start);
}

self.addEventListener("message", powWorkerMessage);
Loading