86 lines
2.4 KiB
PHP
86 lines
2.4 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Jinove\Vinoteca;
|
|
|
|
use AltchaOrg\Altcha\Algorithm\Pbkdf2;
|
|
use AltchaOrg\Altcha\Altcha as Library;
|
|
use AltchaOrg\Altcha\CreateChallengeOptions;
|
|
use AltchaOrg\Altcha\Payload;
|
|
use AltchaOrg\Altcha\VerifySolutionOptions;
|
|
use Bitrix\Main\Application;
|
|
|
|
class Altcha
|
|
{
|
|
private const COST = 2000;
|
|
private const COUNTER_MIN = 1000;
|
|
private const COUNTER_MAX = 2000;
|
|
private const TTL = 1200;
|
|
private const MAX_PAYLOAD = 4000;
|
|
|
|
public static function challenge(): ?array
|
|
{
|
|
$library = self::library();
|
|
if ($library === null) {
|
|
return null;
|
|
}
|
|
|
|
return $library->createChallenge(new CreateChallengeOptions(
|
|
algorithm: new Pbkdf2(),
|
|
cost: self::COST,
|
|
counter: random_int(self::COUNTER_MIN, self::COUNTER_MAX),
|
|
expiresAt: time() + self::TTL,
|
|
))->toArray();
|
|
}
|
|
|
|
public static function verify(string $raw): bool
|
|
{
|
|
$library = self::library();
|
|
if ($library === null || $raw === "" || strlen($raw) > self::MAX_PAYLOAD) {
|
|
return false;
|
|
}
|
|
try {
|
|
$payload = Payload::fromBase64($raw);
|
|
$result = $library->verifySolution(new VerifySolutionOptions(algorithm: new Pbkdf2(), payload: $payload));
|
|
} catch (\Throwable) {
|
|
return false;
|
|
}
|
|
if (!$result->verified || $payload->challenge->signature === null) {
|
|
return false;
|
|
}
|
|
|
|
return self::markUsed($payload->challenge->signature);
|
|
}
|
|
|
|
private static function markUsed(string $signature): bool
|
|
{
|
|
$handle = @fopen(self::dir() . "/altcha-used/" . hash("sha256", $signature), "x");
|
|
if (!$handle) {
|
|
return false;
|
|
}
|
|
fclose($handle);
|
|
if (random_int(1, 50) === 1) {
|
|
foreach (glob(self::dir() . "/altcha-used/*") ?: [] as $old) {
|
|
if (filemtime($old) < time() - 3600) {
|
|
@unlink($old);
|
|
}
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
private static function library(): ?Library
|
|
{
|
|
$key = trim((string)@file_get_contents(self::dir() . "/altcha.key"));
|
|
|
|
return $key === "" ? null : new Library(hmacSignatureSecret: $key);
|
|
}
|
|
|
|
private static function dir(): string
|
|
{
|
|
return dirname(Application::getDocumentRoot()) . "/data";
|
|
}
|
|
}
|