-
Notifications
You must be signed in to change notification settings - Fork 385
Feature: Proof of Work captcha #4495
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
crhallberg
wants to merge
28
commits into
vufind-org:dev
Choose a base branch
from
crhallberg:pow-captcha
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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 b3b6c80
feat: session id used to generate consistent secrets.
crhallberg 6fc0381
fix: alignment of captcha with comment.
crhallberg 356676b
fix: send less information back with form, since we have a better sta…
crhallberg 35a4318
doc: copyright 2
crhallberg 5a6f033
chore: qa-js-and-scss
crhallberg 843c2ea
chore: php-cs-fixer
crhallberg a21c1e2
doc: rename CAPTCHA
crhallberg 1d3336e
Update module/VuFind/src/VuFind/Captcha/PoW.php
crhallberg 5746da2
doc: update copyright
crhallberg 136e3cb
doc: copyright
crhallberg 04fe429
feat: add Altcha as an option.
crhallberg 6b5884f
fix: woke up in the middle of the night in a cold sweat with the abso…
crhallberg 8ff7271
refactor: pass Altcha instance from Factory.
crhallberg 761e780
rm: unused file since vendor supplies WebComponent.
crhallberg c97bfba
fix: remove postinstall.
crhallberg 8dc7d17
doc: add Altcha LICENSE.
crhallberg 62ca158
remove home-grown pow solution.
crhallberg d06cb50
fix: escape challenge JSON.
crhallberg 7f1b88a
Update config/vufind/config.ini
crhallberg 182f5bd
docs: fix parameter types.
crhallberg a9f9003
style: phpcs
crhallberg a358335
Merge branch 'pow-captcha' of https://github.com/crhallberg/vufind in…
crhallberg d6972fa
Merge branch 'dev' into pow-captcha
crhallberg fb11bf4
Merge branch 'dev' into pow-captcha
demiankatz de5dae0
Fix outdated license text.
demiankatz 826c5a9
Handle garbled input data more robustly.
demiankatz 2e485c6
php-cs-fixer
demiankatz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
crhallberg marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| * 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'); | ||
crhallberg marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| $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); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'; | ||
demiankatz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 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), | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.