hryvinskyi / magento2-verification-code
One-time numeric codes and one-time link tokens for Magento 2: issued for a purpose and a subject, with a lifetime and an attempt limit, stored only as keyed hashes, each accepted once; plus the keyed hasher other modules use for their own one-time secrets.
Package info
github.com/hryvinskyi/magento2-verification-code
Type:magento2-module
pkg:composer/hryvinskyi/magento2-verification-code
Requires
- php: ~8.1.0||~8.2.0||~8.3.0||~8.4.0||~8.5.0
- hryvinskyi/magento2-clock: ^1.0
- magento/framework: *
- magento/module-cron: *
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Issues one-time numeric codes, and optional one-time link tokens, for a purpose and a subject, and answers them: right, wrong, expired, out of entries or unknown. A code has a lifetime and a limited number of entries, is accepted once, and is stored only as a keyed hash. The module also publishes the keyed hasher, for other modules that keep one-time secrets of their own. It has no screen, no setting and no wording a person sees: the module that issues a code delivers it and words every answer.
What it does for a store
-
A code for a purpose and a subject. The purpose names what the code is for, in the caller's own word (1 to 64 characters). The subject names whom or what it is for, such as an e-mail address or an id (1 to 255 characters). A code has 6 to 8 digits, drawn one by one from a cryptographically secure source, so it may start with zero.
-
A new code replaces the old ones. Issuing a code for a purpose and a subject stops every unused code and link token of the same purpose and subject.
-
A lifetime and an entry limit. A code lives at least 60 seconds and allows at least one entry; the caller sets both. Each entry is counted before the code is compared, by one conditional update of the database, so requests that race on one code compare at most as many entries as it allows.
-
Accepted once. A right code is used up. A second entry of the same code is answered unknown. Spaces in an entered code are ignored.
-
A link token. A code may come with a link token (43 characters) for a link in a message. The token belongs to the same code: using either one uses up both. A token cannot be guessed, so it has no entry limit; it obeys the lifetime and is accepted once. A token can be checked without being used, for a page that shows a confirmation button before it acts.
-
The answers.
VerificationStatusis a closed set:Status Value Means VerifiedverifiedRight and live. A verifying call used it up. The result carries the subject. WrongwrongNot the code issued. The entry counted; the result says how many entries are left. ExpiredexpiredThe lifetime ran out. ExhaustedexhaustedEvery allowed entry was used. UnknownunknownNo such code or token, or it was used, replaced or invalidated. -
Invalidate. A caller can stop every unused code and token of a purpose and a subject, for example when the thing they confirm was done another way.
-
Keyed hashes. A code is hashed together with its challenge id, a token together with its purpose, with HMAC-SHA256 under the installation's deployment key. The plain code and token exist only in the result of the call that issued them.
Requirements
- Magento Open Source or Adobe Commerce 2.4.x. The module is built and tested on 2.4.9.
- PHP 8.1 to 8.5.
hryvinskyi/magento2-clock^1.0, and the platform's Cron module.- A deployment key (
crypt/keyinapp/etc/env.php), which every installation has.
Installation
Run from the Magento root.
composer require hryvinskyi/magento2-verification-code
bin/magento module:enable Hryvinskyi_Clock Hryvinskyi_VerificationCode
bin/magento setup:upgrade
bin/magento setup:di:compile # production mode only
bin/magento cache:flush
setup:upgrade creates the table hryvinskyi_verification_code. Verify: bin/magento module:status Hryvinskyi_VerificationCode prints Hryvinskyi_VerificationCode : Module is enabled.
The platform's cron must run, or the used and expired codes are never deleted (see Stored data).
Configuration
None. The caller sets the length, the lifetime and the entry limit of each code it issues.
Issuing and checking a code
Inject Hryvinskyi\VerificationCode\Api\VerificationCodesInterface:
use Hryvinskyi\VerificationCode\Api\VerificationCodesInterface; use Hryvinskyi\VerificationCode\Api\VerificationStatus; public function __construct(private readonly VerificationCodesInterface $codes) { } // Six digits, ten minutes, five entries, with a link token. $issued = $this->codes->issue('quote_approval', $email, 6, 600, 5, true); // Deliver $issued->getCode() and a link holding $issued->getLinkToken(); keep $issued->getChallengeId() // with the visitor (a form field, the session), never the code. $result = $this->codes->verify($challengeId, $enteredCode); if ($result->getStatus() === VerificationStatus::Verified) { $subject = $result->getSubject(); }
| Call | Does |
|---|---|
issue($purpose, $subject, $digits, $lifetimeSeconds, $maxAttempts, $withLinkToken) |
Issues a code and replaces the unused ones of the same purpose and subject. Returns the challenge id (22 characters), the code, the link token or null, and the moment it expires. Throws \InvalidArgumentException for a value outside its range. |
verify($challengeId, $code) |
Checks an entered code and uses up a right one. getAttemptsLeft() is above 0 only with Wrong, and 0 on the last allowed entry. |
checkLinkToken($purpose, $token) |
Tells whether a token is live, without using it. Verified, with the subject, means live. |
verifyLinkToken($purpose, $token) |
Uses a token up. |
invalidate($purpose, $subject) |
Stops every unused code and token of the purpose and subject. |
Only one of two requests that send the right code at the same moment is answered Verified; the other is answered Unknown, or Exhausted when the first took the code's last allowed entry.
The keyed hasher
Hryvinskyi\VerificationCode\Api\KeyedHasherInterface hashes any one-time secret the way the codes are hashed:
hash($value): HMAC-SHA256 under the newest deployment key, 64 lower-case hex characters.matches($value, $hash): whether the hash is the value's HMAC under any deployment key, compared in constant time.candidates($value): the value's HMAC under each key, newest first, to look a stored hash up by value.
All three throw \RuntimeException when the installation has no deployment key. A key added to crypt/key becomes the newest; hashes made under an older key keep matching while that key stays.
Extension points
Every interface under Api/ and the enum VerificationStatus are @api. The module has no pool; a caller builds on VerificationCodesInterface and KeyedHasherInterface.
Stored data
Table hryvinskyi_verification_code, one row per issued code:
| Column | Holds |
|---|---|
code_id |
The row. |
challenge_id |
The public id the code is checked against. Unique. |
purpose |
The purpose, as the caller gave it. |
subject |
The subject, as the caller gave it, in plain text. |
code_hash |
HMAC-SHA256 of the challenge id and the code. |
token_hash |
HMAC-SHA256 of the purpose and the link token; null without a token. Unique. |
attempts, max_attempts |
Entries counted, and entries allowed. |
expires_at, consumed_at, created_at |
When the code expires; when it was used, replaced or invalidated; when it was issued. UTC, to the second. |
The cron job hryvinskyi_verification_code_purge (group default, daily at 03:17) deletes the rows that expired, or were used, more than 24 hours earlier. A dead row is kept that day so that a late entry is still answered expired or unknown.
Limits
- The subject is stored as it is given. A subject that is an e-mail address is personal data in the table. A caller that wants none there passes an id or a hash.
- A row outlives its code. It is deleted by the first purge more than 24 hours after it expired or was used, so it can stay up to two days after that, and its lifetime longer when it was never used. The module has no call that deletes the rows of a subject;
invalidate()stops them and leaves them to the purge. - Issuing is not limited. Every new code replaces the old one and comes with a fresh entry limit, so a caller that lets anyone ask for codes must limit how often a subject gets one. Otherwise each new code gives a guesser a new set of entries.
- Removing a deployment key ends its codes. A code hashed under a key taken out of
crypt/keyis answered wrong on every entry, then exhausted. Its link token is answered unknown. - The cron must run. Without it the table keeps every row.
Registrations
| Where | What |
|---|---|
| Preferences | VerificationCodesInterface, KeyedHasherInterface, IssuedCodeInterface, VerificationResultInterface, and the internal code store and secret generator. |
| Table | hryvinskyi_verification_code. |
| Cron | hryvinskyi_verification_code_purge, 17 3 * * *, group default. |
The module registers no route, setting, ACL resource, command, event or plugin.
Versioning
The package follows Semantic Versioning. What changed in each version is in CHANGELOG.md.
Tests
Run from the Magento root.
- Unit:
vendor/bin/phpunit -c app/code/Hryvinskyi/VerificationCode/phpunit.xml.dist. - Integration: the platform's harness in
dev/tests/integration, one run at a time against its own database.cd dev/tests/integration && php -d memory_limit=4G ../../../vendor/bin/phpunit -c phpunit.xml ../../../app/code/Hryvinskyi/VerificationCode/Test/Integration. A change todb_schema.xmlneeds the harness's database rebuilt. - Static analysis: PHPStan 2.x at level 10 with the package's
phpstan.neon.dist(phpstan analyse -c app/code/Hryvinskyi/VerificationCode/phpstan.neon.dist --level=10, afterbin/magento setup:di:compile), andvendor/bin/phpcs --standard=app/code/Hryvinskyi/VerificationCode/phpcs.xml.dist app/code/Hryvinskyi/VerificationCode.