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"; } }