Add optional self-hosted ALTCHA protection and dependency maintenance
This commit is contained in:
1 parent
3b558409f3
commit
2a2f1d5878
59 files changed
+2648
-12
No files matched your search
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
|
||||
|
||||
class Argon2id implements DeriveKeyInterface
|
||||
{
|
||||
public function getAlgorithmName(): string
|
||||
{
|
||||
return 'ARGON2ID';
|
||||
}
|
||||
|
||||
public function deriveKey(
|
||||
ChallengeParameters $parameters,
|
||||
string $salt,
|
||||
string $password,
|
||||
): DeriveKeyResult {
|
||||
if (!\function_exists('sodium_crypto_pwhash')) {
|
||||
throw new \RuntimeException('ext-sodium is required for Argon2id.');
|
||||
}
|
||||
|
||||
$cost = max(1, $parameters->cost);
|
||||
$memoryCost = max(1, $parameters->memoryCost ?? 32768) * 1024;
|
||||
$keyLength = max(0, $parameters->keyLength);
|
||||
|
||||
$derivedKey = sodium_crypto_pwhash(
|
||||
$keyLength,
|
||||
$password,
|
||||
$salt,
|
||||
$cost,
|
||||
$memoryCost,
|
||||
\SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13,
|
||||
);
|
||||
|
||||
return new DeriveKeyResult($derivedKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
|
||||
|
||||
interface DeriveKeyInterface
|
||||
{
|
||||
public function getAlgorithmName(): string;
|
||||
|
||||
public function deriveKey(
|
||||
ChallengeParameters $parameters,
|
||||
string $salt,
|
||||
string $password,
|
||||
): DeriveKeyResult;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
|
||||
|
||||
class DeriveKeyResult
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $derivedKey,
|
||||
public readonly ?ChallengeParameters $parameterOverrides = null,
|
||||
) {
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
|
||||
use HGCFVendor\AltchaOrg\Altcha\HmacAlgorithm;
|
||||
|
||||
class Pbkdf2 implements DeriveKeyInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly HmacAlgorithm $hmacAlgorithm = HmacAlgorithm::SHA256,
|
||||
) {
|
||||
}
|
||||
|
||||
public function getAlgorithmName(): string
|
||||
{
|
||||
return 'PBKDF2/' . $this->hmacAlgorithm->value;
|
||||
}
|
||||
|
||||
public function deriveKey(
|
||||
ChallengeParameters $parameters,
|
||||
string $salt,
|
||||
string $password,
|
||||
): DeriveKeyResult {
|
||||
$cost = max(1, $parameters->cost);
|
||||
$keyLength = max(0, $parameters->keyLength);
|
||||
|
||||
$derivedKey = hash_pbkdf2(
|
||||
$this->hmacAlgorithm->hashAlgo(),
|
||||
$password,
|
||||
$salt,
|
||||
$cost,
|
||||
$keyLength,
|
||||
true,
|
||||
);
|
||||
|
||||
return new DeriveKeyResult($derivedKey);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
|
||||
|
||||
class Scrypt implements DeriveKeyInterface
|
||||
{
|
||||
public function getAlgorithmName(): string
|
||||
{
|
||||
return 'SCRYPT';
|
||||
}
|
||||
|
||||
public function deriveKey(
|
||||
ChallengeParameters $parameters,
|
||||
string $salt,
|
||||
string $password,
|
||||
): DeriveKeyResult {
|
||||
if (!\function_exists('scrypt')) {
|
||||
throw new \RuntimeException('ext-scrypt is required for Scrypt (https://github.com/DomBlack/php-scrypt).');
|
||||
}
|
||||
|
||||
$cost = max(1, $parameters->cost);
|
||||
$memoryCost = max(1, $parameters->memoryCost ?? 8);
|
||||
$parallelism = max(1, $parameters->parallelism ?? 1);
|
||||
$keyLength = max(0, $parameters->keyLength);
|
||||
|
||||
/** @var string $derivedKey */
|
||||
$derivedKey = scrypt(
|
||||
$password,
|
||||
$salt,
|
||||
$cost,
|
||||
$memoryCost,
|
||||
$parallelism,
|
||||
$keyLength,
|
||||
);
|
||||
|
||||
return new DeriveKeyResult($derivedKey);
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
|
||||
|
||||
class Sha implements DeriveKeyInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ShaAlgorithm $algorithm = ShaAlgorithm::SHA256,
|
||||
) {
|
||||
}
|
||||
|
||||
public function getAlgorithmName(): string
|
||||
{
|
||||
return $this->algorithm->value;
|
||||
}
|
||||
|
||||
public function deriveKey(
|
||||
ChallengeParameters $parameters,
|
||||
string $salt,
|
||||
string $password,
|
||||
): DeriveKeyResult {
|
||||
$algo = $this->algorithm->hashAlgo();
|
||||
$derivedKey = hash($algo, $salt . $password, true);
|
||||
|
||||
$cost = max(1, $parameters->cost);
|
||||
for ($i = 1; $i < $cost; $i++) {
|
||||
$derivedKey = hash($algo, $derivedKey, true);
|
||||
}
|
||||
|
||||
if ($parameters->keyLength > 0 && $parameters->keyLength < \strlen($derivedKey)) {
|
||||
$derivedKey = substr($derivedKey, 0, $parameters->keyLength);
|
||||
}
|
||||
|
||||
return new DeriveKeyResult($derivedKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
|
||||
|
||||
enum ShaAlgorithm: string
|
||||
{
|
||||
case SHA1 = 'SHA-1';
|
||||
case SHA256 = 'SHA-256';
|
||||
case SHA384 = 'SHA-384';
|
||||
case SHA512 = 'SHA-512';
|
||||
|
||||
public function hashAlgo(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::SHA1 => 'sha1',
|
||||
self::SHA256 => 'sha256',
|
||||
self::SHA384 => 'sha384',
|
||||
self::SHA512 => 'sha512',
|
||||
};
|
||||
}
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\Algorithm\DeriveKeyInterface;
|
||||
|
||||
class Altcha
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ?string $hmacSignatureSecret = null,
|
||||
private readonly ?string $hmacKeySignatureSecret = null,
|
||||
private readonly HmacAlgorithm $hmacAlgorithm = HmacAlgorithm::SHA256,
|
||||
) {
|
||||
}
|
||||
|
||||
public function createChallenge(CreateChallengeOptions $options): Challenge
|
||||
{
|
||||
$nonce = $options->nonce ?? bin2hex(random_bytes(16));
|
||||
$salt = $options->salt ?? bin2hex(random_bytes(16));
|
||||
|
||||
$params = new ChallengeParameters(
|
||||
algorithm: $options->algorithm->getAlgorithmName(),
|
||||
nonce: $nonce,
|
||||
salt: $salt,
|
||||
cost: $options->cost,
|
||||
keyLength: $options->keyLength,
|
||||
keyPrefix: $options->keyPrefix,
|
||||
memoryCost: $options->memoryCost,
|
||||
parallelism: $options->parallelism,
|
||||
expiresAt: $options->expiresAt,
|
||||
data: $options->data,
|
||||
);
|
||||
|
||||
$keyPrefix = $params->keyPrefix;
|
||||
$keySignature = null;
|
||||
$keyPrefixLength = $options->keyPrefixLength ?? $params->keyLength / 2;
|
||||
|
||||
if (null !== $options->counter) {
|
||||
$result = $this->deriveKeyForCounter($options->algorithm, $params, $options->counter);
|
||||
$keyPrefix = bin2hex(substr($result, 0, $keyPrefixLength));
|
||||
if (null !== $this->hmacKeySignatureSecret) {
|
||||
$keySignature = $this->hmacHex($result, $this->hmacKeySignatureSecret);
|
||||
}
|
||||
} elseif (empty($keyPrefix)) {
|
||||
// Generate a random prefix of the desired hex length
|
||||
$keyPrefix = bin2hex(random_bytes(max(1, (int) $keyPrefixLength)));
|
||||
}
|
||||
|
||||
$params = new ChallengeParameters(
|
||||
algorithm: $params->algorithm,
|
||||
nonce: $params->nonce,
|
||||
salt: $params->salt,
|
||||
cost: $params->cost,
|
||||
keyLength: $params->keyLength,
|
||||
keyPrefix: $keyPrefix,
|
||||
keySignature: $keySignature,
|
||||
memoryCost: $params->memoryCost,
|
||||
parallelism: $params->parallelism,
|
||||
expiresAt: $params->expiresAt,
|
||||
data: $params->data,
|
||||
);
|
||||
|
||||
$secret = $this->signatureSecret();
|
||||
$signature = null !== $secret ? $this->hmacHex($params->toCanonicalJson(), $secret) : null;
|
||||
|
||||
return new Challenge($params, $signature);
|
||||
}
|
||||
|
||||
public function solveChallenge(SolveChallengeOptions $options): ?Solution
|
||||
{
|
||||
$params = $options->challenge->parameters;
|
||||
$nonceBytes = hex2bin($params->nonce) ?: '';
|
||||
$saltBytes = hex2bin($params->salt) ?: '';
|
||||
$keyPrefix = $params->keyPrefix;
|
||||
$keyPrefixBytes = self::hexToBytes($keyPrefix);
|
||||
|
||||
$startTime = microtime(true);
|
||||
$deadline = $startTime + $options->timeout;
|
||||
$i = 0;
|
||||
|
||||
while (microtime(true) < $deadline) {
|
||||
$counter = $options->start + ($i * $options->step);
|
||||
$password = $nonceBytes . pack('N', $counter);
|
||||
|
||||
$result = $options->algorithm->deriveKey($params, $saltBytes, $password);
|
||||
$derivedKey = $result->derivedKey;
|
||||
|
||||
if (self::hasKeyPrefix($derivedKey, $keyPrefix, $keyPrefixBytes)) {
|
||||
$time = microtime(true) - $startTime;
|
||||
|
||||
return new Solution($counter, bin2hex($derivedKey), $time);
|
||||
}
|
||||
|
||||
$i++;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function verifySolution(VerifySolutionOptions $options): VerifySolutionResult
|
||||
{
|
||||
$startTime = microtime(true);
|
||||
$payload = $options->payload;
|
||||
$params = $payload->challenge->parameters;
|
||||
|
||||
// Check expiration: 0 means no expiry; fractional-second comparison, matching altcha-lib (JS)
|
||||
if ($params->expiresAt) {
|
||||
if ($params->expiresAt < microtime(true)) {
|
||||
return new VerifySolutionResult(
|
||||
verified: false,
|
||||
expired: true,
|
||||
time: microtime(true) - $startTime,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Verify challenge signature. Like altcha-lib (JS) there is no unsigned mode: a missing
|
||||
// signature, or a verifier without a signature secret, can never verify.
|
||||
$secret = $this->signatureSecret();
|
||||
$signature = $payload->challenge->signature;
|
||||
try {
|
||||
$canonicalJson = $params->toCanonicalJson();
|
||||
} catch (\JsonException) {
|
||||
$canonicalJson = null; // e.g. invalid UTF-8 in parameters passed as a PHP array
|
||||
}
|
||||
if (
|
||||
null === $secret
|
||||
|| null === $signature
|
||||
|| null === $canonicalJson
|
||||
|| !hash_equals($this->hmacHex($canonicalJson, $secret), $signature)
|
||||
) {
|
||||
return new VerifySolutionResult(
|
||||
verified: false,
|
||||
invalidSignature: true,
|
||||
time: microtime(true) - $startTime,
|
||||
);
|
||||
}
|
||||
|
||||
// Fast path: the challenge carries an HMAC of the raw derived key bytes. A mismatch is final
|
||||
// (no fallback to re-derivation), matching altcha-lib (JS).
|
||||
if (null !== $params->keySignature && null !== $this->hmacKeySignatureSecret) {
|
||||
$derivedKeyBytes = self::hexToBytes($payload->solution->derivedKey);
|
||||
$verified = null !== $derivedKeyBytes
|
||||
&& hash_equals($params->keySignature, $this->hmacHex($derivedKeyBytes, $this->hmacKeySignatureSecret));
|
||||
|
||||
return new VerifySolutionResult(
|
||||
verified: $verified,
|
||||
invalidSolution: $verified ? null : true,
|
||||
time: microtime(true) - $startTime,
|
||||
);
|
||||
}
|
||||
|
||||
// Full re-derivation path
|
||||
$nonceBytes = hex2bin($params->nonce) ?: '';
|
||||
$saltBytes = hex2bin($params->salt) ?: '';
|
||||
$password = $nonceBytes . pack('N', $payload->solution->counter);
|
||||
|
||||
$result = $options->algorithm->deriveKey($params, $saltBytes, $password);
|
||||
$derivedKeyHex = bin2hex($result->derivedKey);
|
||||
|
||||
if (!hash_equals($derivedKeyHex, $payload->solution->derivedKey)) {
|
||||
return new VerifySolutionResult(
|
||||
verified: false,
|
||||
invalidSolution: true,
|
||||
time: microtime(true) - $startTime,
|
||||
);
|
||||
}
|
||||
|
||||
// Verify the derived key starts with the required prefix
|
||||
$keyPrefix = $params->keyPrefix;
|
||||
if (!self::hasKeyPrefix($result->derivedKey, $keyPrefix, self::hexToBytes($keyPrefix))) {
|
||||
return new VerifySolutionResult(
|
||||
verified: false,
|
||||
invalidSolution: true,
|
||||
time: microtime(true) - $startTime,
|
||||
);
|
||||
}
|
||||
|
||||
return new VerifySolutionResult(
|
||||
verified: true,
|
||||
time: microtime(true) - $startTime,
|
||||
);
|
||||
}
|
||||
|
||||
private function deriveKeyForCounter(DeriveKeyInterface $algorithm, ChallengeParameters $params, int $counter): string
|
||||
{
|
||||
$nonceBytes = hex2bin($params->nonce) ?: '';
|
||||
$saltBytes = hex2bin($params->salt) ?: '';
|
||||
$password = $nonceBytes . pack('N', $counter);
|
||||
|
||||
$result = $algorithm->deriveKey($params, $saltBytes, $password);
|
||||
|
||||
return $result->derivedKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* An empty secret counts as unset, matching altcha-lib (JS).
|
||||
*/
|
||||
private function signatureSecret(): ?string
|
||||
{
|
||||
return '' === $this->hmacSignatureSecret ? null : $this->hmacSignatureSecret;
|
||||
}
|
||||
|
||||
private function hmacHex(string $data, string $key): string
|
||||
{
|
||||
return bin2hex(hash_hmac($this->hmacAlgorithm->hashAlgo(), $data, $key, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes an even-length hex string; returns null for anything else (no hex2bin warning).
|
||||
*/
|
||||
private static function hexToBytes(string $hex): ?string
|
||||
{
|
||||
return 1 === preg_match('/\A(?:[0-9a-fA-F]{2})*\z/', $hex) ? (string) hex2bin($hex) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Even-length prefixes compare bytes; odd-length (half-byte) prefixes compare the lowercase
|
||||
* hex string, matching altcha-lib (JS).
|
||||
*/
|
||||
private static function hasKeyPrefix(string $derivedKey, string $keyPrefix, ?string $keyPrefixBytes): bool
|
||||
{
|
||||
return null !== $keyPrefixBytes
|
||||
? str_starts_with($derivedKey, $keyPrefixBytes)
|
||||
: str_starts_with(bin2hex($derivedKey), $keyPrefix);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
class Challenge
|
||||
{
|
||||
public function __construct(
|
||||
public readonly ChallengeParameters $parameters,
|
||||
public readonly ?string $signature = null,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$arr = ['parameters' => $this->parameters->toArray()];
|
||||
if (null !== $this->signature) {
|
||||
$arr['signature'] = $this->signature;
|
||||
}
|
||||
|
||||
return $arr;
|
||||
}
|
||||
|
||||
public function toJson(): string
|
||||
{
|
||||
return json_encode($this->toArray(), \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE) ?: '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $arr
|
||||
*/
|
||||
public static function fromArray(array $arr): self
|
||||
{
|
||||
if (!isset($arr['parameters']) || !\is_array($arr['parameters'])) {
|
||||
throw new \InvalidArgumentException('Invalid challenge data: expected "parameters" (array).');
|
||||
}
|
||||
|
||||
/** @var array<string, mixed> $parameters */
|
||||
$parameters = $arr['parameters'];
|
||||
|
||||
return new self(
|
||||
parameters: ChallengeParameters::fromArray($parameters),
|
||||
signature: isset($arr['signature']) && \is_string($arr['signature']) ? $arr['signature'] : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
class ChallengeParameters
|
||||
{
|
||||
/**
|
||||
* @param null|array<array-key, mixed> $data JSON object; numeric-string keys become int keys in PHP
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $algorithm,
|
||||
public readonly string $nonce,
|
||||
public readonly string $salt,
|
||||
public readonly int $cost,
|
||||
public readonly int $keyLength = 32,
|
||||
public readonly string $keyPrefix = '',
|
||||
public readonly ?string $keySignature = null,
|
||||
public readonly ?int $memoryCost = null,
|
||||
public readonly ?int $parallelism = null,
|
||||
public readonly int|float|null $expiresAt = null,
|
||||
public readonly ?array $data = null,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$arr = [
|
||||
'algorithm' => $this->algorithm,
|
||||
'cost' => $this->cost,
|
||||
'keyLength' => $this->keyLength,
|
||||
'keyPrefix' => $this->keyPrefix,
|
||||
'nonce' => $this->nonce,
|
||||
'salt' => $this->salt,
|
||||
];
|
||||
|
||||
if (null !== $this->keySignature) {
|
||||
$arr['keySignature'] = $this->keySignature;
|
||||
}
|
||||
if (null !== $this->memoryCost) {
|
||||
$arr['memoryCost'] = $this->memoryCost;
|
||||
}
|
||||
if (null !== $this->parallelism) {
|
||||
$arr['parallelism'] = $this->parallelism;
|
||||
}
|
||||
if (null !== $this->expiresAt) {
|
||||
$arr['expiresAt'] = $this->expiresAt;
|
||||
}
|
||||
if (null !== $this->data) {
|
||||
// `data` is a JSON object (JS: Record<string, …>); PHP can't tell `{}`/`{"0": …}` from a list.
|
||||
$arr['data'] = array_is_list($this->data) ? (object) $this->data : $this->data;
|
||||
}
|
||||
|
||||
ksort($arr);
|
||||
|
||||
return $arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Byte-for-byte equal to altcha-lib (JS) `JSON.stringify(sortKeys(parameters))`.
|
||||
*
|
||||
* @throws \JsonException if a string is not valid UTF-8
|
||||
*/
|
||||
public function toCanonicalJson(): string
|
||||
{
|
||||
return self::encodeCanonical($this->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $sortKeys false inside lists: JS `sortKeys()` returns arrays (and their contents) untouched
|
||||
*/
|
||||
private static function encodeCanonical(mixed $value, bool $sortKeys = true): string
|
||||
{
|
||||
if (\is_array($value) && array_is_list($value)) {
|
||||
return '[' . implode(',', array_map(static fn (mixed $item): string => self::encodeCanonical($item, false), $value)) . ']';
|
||||
}
|
||||
if (\is_array($value) || $value instanceof \stdClass) {
|
||||
$value = (array) $value;
|
||||
// PHP turns numeric-string keys into ints; JS keys are always strings.
|
||||
$keys = array_map(strval(...), array_keys($value));
|
||||
usort($keys, static fn (string $a, string $b): int => self::compareKeys($a, $b, $sortKeys));
|
||||
$members = array_map(
|
||||
static fn (string $key): string => self::encodeCanonical($key) . ':' . self::encodeCanonical($value[$key], $sortKeys),
|
||||
$keys,
|
||||
);
|
||||
|
||||
return '{' . implode(',', $members) . '}';
|
||||
}
|
||||
if (\is_float($value) || (\is_int($value) && abs($value) > 2 ** 53)) {
|
||||
return self::encodeJsNumber((float) $value);
|
||||
}
|
||||
|
||||
return json_encode(
|
||||
$value,
|
||||
\JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_LINE_TERMINATORS | \JSON_THROW_ON_ERROR,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* JS property enumeration order: array-index keys ("0"…"4294967294") first in numeric order, then the
|
||||
* remaining keys sorted (objects rebuilt by `sortKeys()`) or in insertion order (stable `usort`).
|
||||
*/
|
||||
private static function compareKeys(string $a, string $b, bool $sortKeys): int
|
||||
{
|
||||
$aIndex = self::arrayIndex($a);
|
||||
$bIndex = self::arrayIndex($b);
|
||||
if (null !== $aIndex || null !== $bIndex) {
|
||||
return (null === $aIndex ? 1 : 0) <=> (null === $bIndex ? 1 : 0) ?: $aIndex <=> $bIndex;
|
||||
}
|
||||
|
||||
return $sortKeys ? self::compareUtf16($a, $b) : 0;
|
||||
}
|
||||
|
||||
private static function arrayIndex(string $key): ?int
|
||||
{
|
||||
return 1 === preg_match('/\A(?:0|[1-9][0-9]{0,9})\z/', $key) && (int) $key <= 4294967294 ? (int) $key : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares UTF-8 strings in UTF-16 code unit order (JS `Array.prototype.sort`): identical to byte
|
||||
* order except that U+E000–U+FFFF (lead bytes EE, EF) sorts after supplementary characters
|
||||
* (lead bytes F0–F4, surrogate pairs in UTF-16).
|
||||
*/
|
||||
private static function compareUtf16(string $a, string $b): int
|
||||
{
|
||||
$common = strspn($a ^ $b, "\0");
|
||||
if ($common === min(\strlen($a), \strlen($b))) {
|
||||
return \strlen($a) <=> \strlen($b);
|
||||
}
|
||||
$x = \ord($a[$common]);
|
||||
$y = \ord($b[$common]);
|
||||
if ($x >= 0xEE && $y >= 0xEE) {
|
||||
$x = $x < 0xF0 ? $x + 0x10 : $x;
|
||||
$y = $y < 0xF0 ? $y + 0x10 : $y;
|
||||
}
|
||||
|
||||
return $x <=> $y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a double like JS `Number.prototype.toString()`: shortest round-trip digits, plain notation
|
||||
* for 1e-6 <= |n| < 1e21, otherwise `d[.ddd]e±x`.
|
||||
*/
|
||||
private static function encodeJsNumber(float $value): string
|
||||
{
|
||||
if (!is_finite($value)) {
|
||||
return 'null';
|
||||
}
|
||||
if (0.0 === $value) {
|
||||
return '0';
|
||||
}
|
||||
|
||||
// Shortest digits that round-trip, as coefficient × 10^scale.
|
||||
$abs = abs($value);
|
||||
for ($precision = 0; $precision < 17; $precision++) {
|
||||
[$mantissa, $exponent] = explode('e', \sprintf('%.' . $precision . 'e', $abs));
|
||||
$scale = (int) $exponent - $precision;
|
||||
$coefficient = (int) str_replace('.', '', $mantissa);
|
||||
if ((float) ($coefficient . 'e' . $scale) === $abs) {
|
||||
break;
|
||||
}
|
||||
// At exact powers of two the gap below is half the gap above: the nearest candidate can fail
|
||||
// while the next one up round-trips, and JS picks that one.
|
||||
if ((float) (($coefficient + 1) . 'e' . $scale) === $abs) {
|
||||
$coefficient++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
$sign = $value < 0 ? '-' : '';
|
||||
$digits = rtrim((string) $coefficient, '0');
|
||||
$k = \strlen($digits);
|
||||
$n = $scale + \strlen((string) $coefficient);
|
||||
|
||||
if ($k <= $n && $n <= 21) {
|
||||
return $sign . $digits . str_repeat('0', $n - $k);
|
||||
}
|
||||
if (0 < $n && $n <= 21) {
|
||||
return $sign . substr($digits, 0, $n) . '.' . substr($digits, $n);
|
||||
}
|
||||
if (-6 < $n && $n <= 0) {
|
||||
return $sign . '0.' . str_repeat('0', -$n) . $digits;
|
||||
}
|
||||
|
||||
return $sign . $digits[0] . ($k > 1 ? '.' . substr($digits, 1) : '') . 'e' . ($n > 0 ? '+' : '-') . abs($n - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $arr
|
||||
*/
|
||||
public static function fromArray(array $arr): self
|
||||
{
|
||||
$algorithm = isset($arr['algorithm']) && \is_string($arr['algorithm']) ? $arr['algorithm'] : '';
|
||||
$nonce = isset($arr['nonce']) && \is_string($arr['nonce']) ? $arr['nonce'] : '';
|
||||
$salt = isset($arr['salt']) && \is_string($arr['salt']) ? $arr['salt'] : '';
|
||||
$cost = isset($arr['cost']) && \is_int($arr['cost']) ? $arr['cost'] : 0;
|
||||
$keyLength = isset($arr['keyLength']) && \is_int($arr['keyLength']) ? $arr['keyLength'] : 32;
|
||||
$keyPrefix = isset($arr['keyPrefix']) && \is_string($arr['keyPrefix']) ? $arr['keyPrefix'] : '';
|
||||
$keySignature = isset($arr['keySignature']) && \is_string($arr['keySignature']) ? $arr['keySignature'] : null;
|
||||
$memoryCost = isset($arr['memoryCost']) && \is_int($arr['memoryCost']) ? $arr['memoryCost'] : null;
|
||||
$parallelism = isset($arr['parallelism']) && \is_int($arr['parallelism']) ? $arr['parallelism'] : null;
|
||||
// JS issuers may send a fractional expiresAt (e.g. Date.now() / 1000 + 600); it is signed as-is.
|
||||
$expiresAt = isset($arr['expiresAt']) && (\is_int($arr['expiresAt']) || \is_float($arr['expiresAt'])) ? $arr['expiresAt'] : null;
|
||||
/** @var null|array<array-key, mixed> $data */
|
||||
$data = isset($arr['data']) && (\is_array($arr['data']) || $arr['data'] instanceof \stdClass) ? (array) $arr['data'] : null;
|
||||
|
||||
return new self(
|
||||
algorithm: $algorithm,
|
||||
nonce: $nonce,
|
||||
salt: $salt,
|
||||
cost: $cost,
|
||||
keyLength: $keyLength,
|
||||
keyPrefix: $keyPrefix,
|
||||
keySignature: $keySignature,
|
||||
memoryCost: $memoryCost,
|
||||
parallelism: $parallelism,
|
||||
expiresAt: $expiresAt,
|
||||
data: $data,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\Algorithm\DeriveKeyInterface;
|
||||
|
||||
class CreateChallengeOptions
|
||||
{
|
||||
public readonly int|float|null $expiresAt;
|
||||
|
||||
/**
|
||||
* @param null|array<string, mixed> $data
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly DeriveKeyInterface $algorithm,
|
||||
public readonly int $cost,
|
||||
public readonly int $keyLength = 32,
|
||||
public readonly string $keyPrefix = '00',
|
||||
public readonly ?int $counter = null,
|
||||
public readonly ?int $memoryCost = null,
|
||||
public readonly ?int $parallelism = null,
|
||||
\DateTimeInterface|int|float|null $expiresAt = null,
|
||||
public readonly ?array $data = null,
|
||||
public readonly ?string $nonce = null,
|
||||
public readonly ?string $salt = null,
|
||||
public readonly ?int $keyPrefixLength = null,
|
||||
) {
|
||||
$this->expiresAt = $expiresAt instanceof \DateTimeInterface
|
||||
? $expiresAt->getTimestamp()
|
||||
: $expiresAt;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
enum HmacAlgorithm: string
|
||||
{
|
||||
case SHA256 = 'SHA-256';
|
||||
case SHA384 = 'SHA-384';
|
||||
case SHA512 = 'SHA-512';
|
||||
|
||||
/**
|
||||
* @return non-falsy-string
|
||||
*/
|
||||
public function hashAlgo(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::SHA256 => 'sha256',
|
||||
self::SHA384 => 'sha384',
|
||||
self::SHA512 => 'sha512',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\Http;
|
||||
|
||||
interface HttpClientInterface
|
||||
{
|
||||
/**
|
||||
* @param array<string, string> $headers
|
||||
*/
|
||||
public function send(string $url, string $method, array $headers, string $body, float $timeout): HttpResponse;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\Http;
|
||||
|
||||
class HttpResponse
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $statusCode,
|
||||
public readonly string $body,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\Http;
|
||||
|
||||
/**
|
||||
* Default HttpClientInterface implementation using PHP's built-in stream wrappers.
|
||||
* Requires no additional extension or dependency.
|
||||
*/
|
||||
class StreamHttpClient implements HttpClientInterface
|
||||
{
|
||||
public function send(string $url, string $method, array $headers, string $body, float $timeout): HttpResponse
|
||||
{
|
||||
$headerLines = [];
|
||||
foreach ($headers as $name => $value) {
|
||||
$headerLines[] = $name . ': ' . $value;
|
||||
}
|
||||
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => $method,
|
||||
'header' => implode("\r\n", $headerLines),
|
||||
'content' => $body,
|
||||
'timeout' => $timeout,
|
||||
'ignore_errors' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$errorMessage = null;
|
||||
set_error_handler(static function (int $errno, string $errstr) use (&$errorMessage): bool {
|
||||
$errorMessage = $errstr;
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
try {
|
||||
$handle = fopen($url, 'r', false, $context);
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
}
|
||||
|
||||
if (false === $handle) {
|
||||
throw new \RuntimeException($errorMessage ?? 'Network error while requesting Sentinel API.');
|
||||
}
|
||||
|
||||
$responseBody = stream_get_contents($handle);
|
||||
$meta = stream_get_meta_data($handle);
|
||||
fclose($handle);
|
||||
|
||||
if (false === $responseBody) {
|
||||
throw new \RuntimeException('Failed to read response from Sentinel API.');
|
||||
}
|
||||
|
||||
$statusCode = 0;
|
||||
/** @var list<string> $wrapperData */
|
||||
$wrapperData = $meta['wrapper_data'] ?? [];
|
||||
foreach ($wrapperData as $line) {
|
||||
if (preg_match('#^HTTP/\S+\s+(\d+)#', $line, $matches)) {
|
||||
$statusCode = (int) $matches[1];
|
||||
}
|
||||
}
|
||||
|
||||
return new HttpResponse($statusCode, $responseBody);
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\Algorithm\DeriveKeyInterface;
|
||||
use HGCFVendor\AltchaOrg\Altcha\Algorithm\Pbkdf2;
|
||||
|
||||
class Obfuscator
|
||||
{
|
||||
private const CIPHER = 'aes-256-gcm';
|
||||
private const IV_LENGTH = 12;
|
||||
private const TAG_LENGTH = 16;
|
||||
private const DEFAULT_COST = 5000;
|
||||
private const DEFAULT_KEY_PREFIX_LENGTH = 32;
|
||||
private const DEFAULT_COUNTER_MIN = 20;
|
||||
private const DEFAULT_COUNTER_MAX = 200;
|
||||
|
||||
public function __construct(
|
||||
private readonly Altcha $altcha,
|
||||
private readonly DeriveKeyInterface $algorithm = new Pbkdf2(),
|
||||
) {
|
||||
}
|
||||
|
||||
public function obfuscate(
|
||||
string $data,
|
||||
int $cost = self::DEFAULT_COST,
|
||||
int $counterMin = self::DEFAULT_COUNTER_MIN,
|
||||
int $counterMax = self::DEFAULT_COUNTER_MAX,
|
||||
int $keyPrefixLength = self::DEFAULT_KEY_PREFIX_LENGTH,
|
||||
): string {
|
||||
$counter = random_int($counterMin, $counterMax);
|
||||
|
||||
$challenge = $this->altcha->createChallenge(new CreateChallengeOptions(
|
||||
algorithm: $this->algorithm,
|
||||
cost: $cost,
|
||||
keyLength: 32,
|
||||
keyPrefixLength: $keyPrefixLength,
|
||||
counter: $counter,
|
||||
));
|
||||
|
||||
// The full keyPrefix from challenge creation is the AES key (hex-encoded).
|
||||
// Convert to raw bytes for AES-256-GCM (requires 32 bytes = 64 hex chars).
|
||||
$fullKeyHex = $challenge->parameters->keyPrefix;
|
||||
$aesKey = hex2bin($fullKeyHex) ?: throw new \RuntimeException('Invalid key prefix.');
|
||||
|
||||
// Encrypt the data with AES-256-GCM
|
||||
$iv = random_bytes(self::IV_LENGTH);
|
||||
$tag = '';
|
||||
$ciphertext = openssl_encrypt($data, self::CIPHER, $aesKey, \OPENSSL_RAW_DATA, $iv, $tag, '', self::TAG_LENGTH);
|
||||
if (false === $ciphertext) {
|
||||
throw new \RuntimeException('Encryption failed.');
|
||||
}
|
||||
|
||||
// Truncate the keyPrefix to half (the solver must brute-force the rest)
|
||||
$truncatedKeyPrefix = substr($fullKeyHex, 0, $challenge->parameters->keyLength);
|
||||
|
||||
$params = new ChallengeParameters(
|
||||
algorithm: $challenge->parameters->algorithm,
|
||||
nonce: $challenge->parameters->nonce,
|
||||
salt: $challenge->parameters->salt,
|
||||
cost: $challenge->parameters->cost,
|
||||
keyLength: $challenge->parameters->keyLength,
|
||||
keyPrefix: $truncatedKeyPrefix,
|
||||
memoryCost: $challenge->parameters->memoryCost,
|
||||
parallelism: $challenge->parameters->parallelism,
|
||||
);
|
||||
|
||||
$output = [
|
||||
'parameters' => $params->toArray(),
|
||||
'cipher' => [
|
||||
'iv' => bin2hex($iv),
|
||||
'data' => bin2hex($ciphertext . $tag),
|
||||
],
|
||||
];
|
||||
|
||||
return base64_encode(json_encode($output, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE) ?: '');
|
||||
}
|
||||
|
||||
public function deobfuscate(
|
||||
string $obfuscatedData,
|
||||
float $timeout = 30.0,
|
||||
): string {
|
||||
$json = base64_decode($obfuscatedData, true);
|
||||
if (false === $json) {
|
||||
throw new \InvalidArgumentException('Unable to parse obfuscated data.');
|
||||
}
|
||||
|
||||
/** @var null|array{parameters: array<string, mixed>, parameters: null|array<string, mixed>, cipher: null|array{iv: string, data: string}} $parsed */
|
||||
$parsed = json_decode($json, true);
|
||||
if (!\is_array($parsed) || !isset($parsed['parameters'], $parsed['cipher'])) {
|
||||
throw new \InvalidArgumentException('Invalid obfuscated data format.');
|
||||
}
|
||||
|
||||
$params = ChallengeParameters::fromArray($parsed['parameters']);
|
||||
$challenge = new Challenge($params, null);
|
||||
|
||||
// Solve the challenge to recover the full derived key
|
||||
$solution = $this->altcha->solveChallenge(new SolveChallengeOptions(
|
||||
challenge: $challenge,
|
||||
algorithm: $this->algorithm,
|
||||
timeout: $timeout,
|
||||
));
|
||||
|
||||
if (null === $solution) {
|
||||
throw new \RuntimeException('Unable to find solution.');
|
||||
}
|
||||
|
||||
// The full derived key (hex) is the AES key
|
||||
$aesKey = hex2bin($solution->derivedKey) ?: throw new \RuntimeException('Invalid derived key.');
|
||||
|
||||
$iv = hex2bin($parsed['cipher']['iv']) ?: throw new \RuntimeException('Invalid cipher IV.');
|
||||
$ciphertextWithTag = hex2bin($parsed['cipher']['data']) ?: throw new \RuntimeException('Invalid cipher data.');
|
||||
|
||||
// Separate ciphertext and GCM auth tag
|
||||
$ciphertext = substr($ciphertextWithTag, 0, -self::TAG_LENGTH);
|
||||
$tag = substr($ciphertextWithTag, -self::TAG_LENGTH);
|
||||
|
||||
$decrypted = openssl_decrypt($ciphertext, self::CIPHER, $aesKey, \OPENSSL_RAW_DATA, $iv, $tag);
|
||||
if (false === $decrypted) {
|
||||
throw new \RuntimeException('Decryption failed.');
|
||||
}
|
||||
|
||||
return $decrypted;
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
class Payload
|
||||
{
|
||||
public function __construct(
|
||||
public readonly Challenge $challenge,
|
||||
public readonly Solution $solution,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'challenge' => $this->challenge->toArray(),
|
||||
'solution' => $this->solution->toArray(),
|
||||
];
|
||||
}
|
||||
|
||||
public function toJson(): string
|
||||
{
|
||||
return json_encode($this->toArray(), \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE) ?: '';
|
||||
}
|
||||
|
||||
public function toBase64(): string
|
||||
{
|
||||
return base64_encode($this->toJson());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $arr
|
||||
*/
|
||||
public static function fromArray(array $arr): self
|
||||
{
|
||||
if (!isset($arr['challenge'], $arr['solution']) || !\is_array($arr['challenge']) || !\is_array($arr['solution'])) {
|
||||
throw new \InvalidArgumentException('Invalid payload data: expected "challenge" and "solution".');
|
||||
}
|
||||
|
||||
/** @var array<string, mixed> $challenge */
|
||||
$challenge = $arr['challenge'];
|
||||
/** @var array<string, mixed> $solution */
|
||||
$solution = $arr['solution'];
|
||||
|
||||
return new self(
|
||||
challenge: Challenge::fromArray($challenge),
|
||||
solution: Solution::fromArray($solution),
|
||||
);
|
||||
}
|
||||
|
||||
public static function fromBase64(string $payload): self
|
||||
{
|
||||
$decoded = base64_decode($payload, true);
|
||||
if (false === $decoded) {
|
||||
throw new \InvalidArgumentException('Invalid base64-encoded payload.');
|
||||
}
|
||||
|
||||
try {
|
||||
$data = json_decode($decoded, true, 512, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
throw new \InvalidArgumentException('Invalid JSON in payload.', previous: $e);
|
||||
}
|
||||
|
||||
if (!\is_array($data)) {
|
||||
throw new \InvalidArgumentException('Invalid payload: expected a JSON object.');
|
||||
}
|
||||
|
||||
/** @var array<string, mixed> $decodedData */
|
||||
$decodedData = $data;
|
||||
|
||||
return self::fromArray($decodedData);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
enum RetryBackoff
|
||||
{
|
||||
case Fixed;
|
||||
case Exponential;
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\Http\HttpResponse;
|
||||
use HGCFVendor\AltchaOrg\Altcha\Http\StreamHttpClient;
|
||||
|
||||
class Sentinel
|
||||
{
|
||||
/**
|
||||
* Verifies a payload remotely via the ALTCHA Sentinel `/v1/verify/signature` API,
|
||||
* instead of verifying the HMAC signature locally.
|
||||
*/
|
||||
public static function verify(VerifyServerOptions $options): VerifyServerResult
|
||||
{
|
||||
$httpClient = $options->httpClient ?? new StreamHttpClient();
|
||||
|
||||
$body = ['payload' => $options->payload];
|
||||
if (null !== $options->secret) {
|
||||
$body['secret'] = $options->secret;
|
||||
}
|
||||
$bodyJson = json_encode($body, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE) ?: '{}';
|
||||
|
||||
$headers = ['Content-Type' => 'application/json', ...$options->headers];
|
||||
|
||||
for ($attempt = 0; $attempt <= $options->retries; $attempt++) {
|
||||
try {
|
||||
$response = $httpClient->send($options->url, 'POST', $headers, $bodyJson, $options->timeout);
|
||||
|
||||
return self::handleResponse($response);
|
||||
} catch (\Throwable $e) {
|
||||
if ($attempt >= $options->retries) {
|
||||
return new VerifyServerResult(verified: false, reason: $e->getMessage());
|
||||
}
|
||||
|
||||
$backoffMs = RetryBackoff::Fixed === $options->retryBackoff
|
||||
? $options->retryDelay
|
||||
: $options->retryDelay * 2 ** $attempt;
|
||||
usleep($backoffMs * 1000);
|
||||
}
|
||||
}
|
||||
|
||||
return new VerifyServerResult(verified: false, reason: 'NETWORK_ERROR');
|
||||
}
|
||||
|
||||
/**
|
||||
* Interprets an HTTP response. Returns a terminal (non-retryable) VerifyServerResult,
|
||||
* or throws to trigger the retry path for non-2xx/non-400 statuses and unparseable bodies.
|
||||
*/
|
||||
private static function handleResponse(HttpResponse $response): VerifyServerResult
|
||||
{
|
||||
if (400 === $response->statusCode) {
|
||||
$data = json_decode($response->body, true);
|
||||
$reason = \is_array($data) && isset($data['error']) && \is_string($data['error']) ? $data['error'] : 'HTTP_400';
|
||||
|
||||
return new VerifyServerResult(verified: false, reason: $reason);
|
||||
}
|
||||
|
||||
if ($response->statusCode < 200 || $response->statusCode >= 300) {
|
||||
throw new \RuntimeException('HTTP_' . $response->statusCode);
|
||||
}
|
||||
|
||||
$data = json_decode($response->body, true);
|
||||
if (!\is_array($data)) {
|
||||
throw new \RuntimeException('Invalid JSON response from Sentinel API.');
|
||||
}
|
||||
|
||||
/** @var array<string, mixed> $result */
|
||||
$result = $data;
|
||||
|
||||
return VerifyServerResult::fromArray($result);
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
class ServerSignature
|
||||
{
|
||||
/** @var list<string> */
|
||||
private const ARRAY_KEYS = ['fields', 'reasons'];
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed>|string $data
|
||||
*/
|
||||
public static function verifyServerSignature(
|
||||
string|array $data,
|
||||
string $hmacKey,
|
||||
): ServerSignatureVerification {
|
||||
$startTime = hrtime(true);
|
||||
$payload = self::parsePayload($data);
|
||||
|
||||
if (!$payload) {
|
||||
return new ServerSignatureVerification(
|
||||
verified: false,
|
||||
verificationData: null,
|
||||
);
|
||||
}
|
||||
|
||||
$hashAlgo = $payload['hmacAlgorithm']->hashAlgo();
|
||||
$hash = hash($hashAlgo, $payload['verificationData'], true);
|
||||
$expectedSignature = bin2hex(hash_hmac($hashAlgo, $hash, $hmacKey, true));
|
||||
|
||||
$verificationData = self::parseVerificationData($payload['verificationData']);
|
||||
|
||||
$invalidSignature = !hash_equals($expectedSignature, $payload['signature']);
|
||||
$invalidSolution = !$payload['verified'] || !($verificationData['verified'] ?? false);
|
||||
|
||||
$expire = $verificationData['expire'] ?? null;
|
||||
$expired = \is_int($expire) && $expire < time();
|
||||
|
||||
$verified = !$invalidSignature && !$invalidSolution && !$expired;
|
||||
|
||||
$elapsedTime = (hrtime(true) - $startTime) / 1e9;
|
||||
|
||||
return new ServerSignatureVerification(
|
||||
verified: $verified,
|
||||
verificationData: $verificationData,
|
||||
expired: $expired,
|
||||
invalidSignature: $invalidSignature,
|
||||
invalidSolution: $invalidSolution,
|
||||
time: $elapsedTime,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse URL-encoded verification data with auto type detection.
|
||||
*/
|
||||
public static function parseVerificationData(string $data): ServerSignatureVerificationData
|
||||
{
|
||||
parse_str($data, $params);
|
||||
|
||||
/** @var array<string, mixed> $result */
|
||||
$result = [];
|
||||
|
||||
foreach ($params as $key => $value) {
|
||||
$key = (string) $key;
|
||||
|
||||
if (!\is_string($value)) {
|
||||
$result[$key] = $value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (\in_array($key, self::ARRAY_KEYS, true)) {
|
||||
$result[$key] = '' !== $value ? explode(',', $value) : [];
|
||||
continue;
|
||||
}
|
||||
|
||||
if ('true' === $value) {
|
||||
$result[$key] = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ('false' === $value) {
|
||||
$result[$key] = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^\d+$/', $value)) {
|
||||
$result[$key] = (int) $value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^\d+\.\d+$/', $value)) {
|
||||
$result[$key] = (float) $value;
|
||||
continue;
|
||||
}
|
||||
|
||||
$result[$key] = $value;
|
||||
}
|
||||
|
||||
return new ServerSignatureVerificationData($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $formData
|
||||
* @param list<string> $fields
|
||||
*/
|
||||
public static function verifyFieldsHash(
|
||||
array $formData,
|
||||
array $fields,
|
||||
string $fieldsHash,
|
||||
HmacAlgorithm $hmacAlgorithm = HmacAlgorithm::SHA256,
|
||||
): bool {
|
||||
$lines = [];
|
||||
foreach ($fields as $field) {
|
||||
$value = $formData[$field] ?? null;
|
||||
$lines[] = \is_scalar($value) ? (string) $value : '';
|
||||
}
|
||||
$joinedData = implode("\n", $lines);
|
||||
$computedHash = hash($hmacAlgorithm->hashAlgo(), $joinedData);
|
||||
|
||||
return $computedHash === $fieldsHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed>|string $data
|
||||
*
|
||||
* @return null|array{hmacAlgorithm: HmacAlgorithm, verificationData: string, signature: string, verified: bool}
|
||||
*/
|
||||
private static function parsePayload(string|array $data): ?array
|
||||
{
|
||||
if (\is_string($data)) {
|
||||
$decoded = base64_decode($data, true);
|
||||
if (!$decoded) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$data = json_decode($decoded, true, 2, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException|\ValueError) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!\is_array($data) || empty($data)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($data['algorithm'], $data['verificationData'], $data['signature'], $data['verified'])
|
||||
|| !\is_string($data['algorithm'])
|
||||
|| !\is_string($data['verificationData'])
|
||||
|| !\is_string($data['signature'])
|
||||
|| !\is_bool($data['verified'])
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$hmacAlgorithm = HmacAlgorithm::tryFrom($data['algorithm']);
|
||||
if (!$hmacAlgorithm) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'hmacAlgorithm' => $hmacAlgorithm,
|
||||
'verificationData' => $data['verificationData'],
|
||||
'signature' => $data['signature'],
|
||||
'verified' => $data['verified'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
class ServerSignatureVerification
|
||||
{
|
||||
public function __construct(
|
||||
public readonly bool $verified,
|
||||
public readonly ?ServerSignatureVerificationData $verificationData,
|
||||
public readonly bool $expired = false,
|
||||
public readonly bool $invalidSignature = false,
|
||||
public readonly bool $invalidSolution = false,
|
||||
public readonly float $time = 0.0,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
/**
|
||||
* Generic verification data parsed from server signature payload.
|
||||
*
|
||||
* Supports property access ($data->key) and array access ($data['key']).
|
||||
*
|
||||
* @implements \ArrayAccess<string, mixed>
|
||||
*
|
||||
* @property mixed $verified
|
||||
* @property mixed $expire
|
||||
* @property mixed $score
|
||||
* @property mixed $fields
|
||||
* @property mixed $fieldsHash
|
||||
* @property mixed $reasons
|
||||
* @property mixed $classification
|
||||
* @property mixed $country
|
||||
* @property mixed $detectedLanguage
|
||||
* @property mixed $email
|
||||
* @property mixed $time
|
||||
*/
|
||||
class ServerSignatureVerificationData implements \ArrayAccess, \JsonSerializable
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly array $data = [],
|
||||
) {
|
||||
}
|
||||
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
return $this->data[$name] ?? null;
|
||||
}
|
||||
|
||||
public function __isset(string $name): bool
|
||||
{
|
||||
return isset($this->data[$name]);
|
||||
}
|
||||
|
||||
public function offsetExists(mixed $offset): bool
|
||||
{
|
||||
return isset($this->data[$offset]);
|
||||
}
|
||||
|
||||
public function offsetGet(mixed $offset): mixed
|
||||
{
|
||||
return $this->data[$offset] ?? null;
|
||||
}
|
||||
|
||||
public function offsetSet(mixed $offset, mixed $value): void
|
||||
{
|
||||
throw new \LogicException('ServerSignatureVerificationData is read-only.');
|
||||
}
|
||||
|
||||
public function offsetUnset(mixed $offset): void
|
||||
{
|
||||
throw new \LogicException('ServerSignatureVerificationData is read-only.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
class Solution
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $counter,
|
||||
public readonly string $derivedKey,
|
||||
public readonly ?float $time = null,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$arr = [
|
||||
'counter' => $this->counter,
|
||||
'derivedKey' => $this->derivedKey,
|
||||
];
|
||||
if (null !== $this->time) {
|
||||
$arr['time'] = $this->time;
|
||||
}
|
||||
|
||||
return $arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $arr
|
||||
*/
|
||||
public static function fromArray(array $arr): self
|
||||
{
|
||||
if (!isset($arr['counter'], $arr['derivedKey']) || !\is_int($arr['counter']) || !\is_string($arr['derivedKey'])) {
|
||||
throw new \InvalidArgumentException('Invalid solution data: expected "counter" (int) and "derivedKey" (string).');
|
||||
}
|
||||
|
||||
return new self(
|
||||
counter: $arr['counter'],
|
||||
derivedKey: $arr['derivedKey'],
|
||||
time: isset($arr['time']) && is_numeric($arr['time']) ? (float) $arr['time'] : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\Algorithm\DeriveKeyInterface;
|
||||
|
||||
class SolveChallengeOptions
|
||||
{
|
||||
public function __construct(
|
||||
public readonly Challenge $challenge,
|
||||
public readonly DeriveKeyInterface $algorithm,
|
||||
public readonly int $start = 0,
|
||||
public readonly int $step = 1,
|
||||
public readonly float $timeout = 30.0,
|
||||
) {
|
||||
}
|
||||
}
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Hasher;
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\HasherInterface;
|
||||
|
||||
class Altcha
|
||||
{
|
||||
/**
|
||||
* @param string $hmacKey Required HMAC key for challenge calculation and solution verification.
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly string $hmacKey,
|
||||
private readonly HasherInterface $hasher = new Hasher(),
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return null|array<array-key, mixed>
|
||||
*/
|
||||
private function decodePayload(string $payload): ?array
|
||||
{
|
||||
$decoded = base64_decode($payload, true);
|
||||
|
||||
if (!$decoded) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$data = json_decode($decoded, true, 2, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException|\ValueError) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!\is_array($data) || empty($data)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed>|string $data
|
||||
*/
|
||||
private function verifyAndBuildSolutionPayload(string|array $data): ?Payload
|
||||
{
|
||||
if (\is_string($data)) {
|
||||
$data = $this->decodePayload($data);
|
||||
}
|
||||
|
||||
if (null === $data
|
||||
|| !isset($data['algorithm'], $data['challenge'], $data['number'], $data['salt'], $data['signature'])
|
||||
|| !\is_string($data['algorithm'])
|
||||
|| !\is_string($data['challenge'])
|
||||
|| !\is_int($data['number'])
|
||||
|| !\is_string($data['salt'])
|
||||
|| !\is_string($data['signature'])
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$algorithm = Algorithm::tryFrom($data['algorithm']);
|
||||
|
||||
if (!$algorithm) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Payload($algorithm, $data['challenge'], $data['number'], $data['salt'], $data['signature']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed>|string $data
|
||||
*/
|
||||
private function verifyAndBuildServerSignaturePayload(string|array $data): ?ServerSignaturePayload
|
||||
{
|
||||
if (\is_string($data)) {
|
||||
$data = $this->decodePayload($data);
|
||||
}
|
||||
|
||||
if (null === $data
|
||||
|| !isset($data['algorithm'], $data['verificationData'], $data['signature'], $data['verified'])
|
||||
|| !\is_string($data['algorithm'])
|
||||
|| !\is_string($data['verificationData'])
|
||||
|| !\is_string($data['signature'])
|
||||
|| !\is_bool($data['verified'])
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$algorithm = Algorithm::tryFrom($data['algorithm']);
|
||||
|
||||
if (!$algorithm) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new ServerSignaturePayload($algorithm, $data['verificationData'], $data['signature'], $data['verified']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new challenge for ALTCHA.
|
||||
*
|
||||
* @return Challenge The challenge data to be passed to ALTCHA.
|
||||
*/
|
||||
public function createChallenge(BaseChallengeOptions $options = new ChallengeOptions()): Challenge
|
||||
{
|
||||
$challenge = $this->hasher->hashHex($options->algorithm, $options->salt . $options->number);
|
||||
$signature = $this->hasher->hashHmacHex($options->algorithm, $challenge, $this->hmacKey);
|
||||
|
||||
return new Challenge($options->algorithm->value, $challenge, $options->maxNumber, $options->salt, $signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies an ALTCHA solution.
|
||||
*
|
||||
* @param array<array-key, mixed>|string $data The solution payload to verify.
|
||||
* @param bool $checkExpires Whether to check if the challenge has expired.
|
||||
*
|
||||
* @return bool True if the solution is valid.
|
||||
*/
|
||||
public function verifySolution(string|array $data, bool $checkExpires = true): bool
|
||||
{
|
||||
$payload = $this->verifyAndBuildSolutionPayload($data);
|
||||
|
||||
if (!$payload) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$params = $this->extractParams($payload);
|
||||
if ($checkExpires && isset($params['expires']) && is_numeric($params['expires'])) {
|
||||
$expireTime = (int) $params['expires'];
|
||||
if (time() > $expireTime) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$challengeOptions = new CheckChallengeOptions(
|
||||
$payload->algorithm,
|
||||
$payload->salt,
|
||||
$payload->number
|
||||
);
|
||||
|
||||
$expectedChallenge = $this->createChallenge($challengeOptions);
|
||||
|
||||
return $expectedChallenge->challenge === $payload->challenge
|
||||
&& $expectedChallenge->signature === $payload->signature;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, array<array-key, mixed>|string>
|
||||
*/
|
||||
private function extractParams(Payload $payload): array
|
||||
{
|
||||
$saltParts = explode('?', $payload->salt);
|
||||
if (\count($saltParts) > 1) {
|
||||
parse_str($saltParts[1], $params);
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies the hash of form fields.
|
||||
*
|
||||
* @param array<string, mixed> $formData The form data to hash.
|
||||
* @param list<string> $fields The fields to include in the hash.
|
||||
* @param string $fieldsHash The expected hash value.
|
||||
* @param Algorithm $algorithm Hashing algorithm (`SHA-1`, `SHA-256`, `SHA-512`).
|
||||
*/
|
||||
public function verifyFieldsHash(array $formData, array $fields, string $fieldsHash, Algorithm $algorithm): bool
|
||||
{
|
||||
$lines = [];
|
||||
foreach ($fields as $field) {
|
||||
$value = $formData[$field] ?? null;
|
||||
$lines[] = \is_scalar($value) ? (string) $value : '';
|
||||
}
|
||||
$joinedData = implode("\n", $lines);
|
||||
$computedHash = $this->hasher->hashHex($algorithm, $joinedData);
|
||||
|
||||
return $computedHash === $fieldsHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies the server signature.
|
||||
*
|
||||
* @param array<array-key, mixed>|string $data The payload to verify (string or `ServerSignaturePayload` array).
|
||||
*/
|
||||
public function verifyServerSignature(string|array $data): ServerSignatureVerification
|
||||
{
|
||||
$payload = $this->verifyAndBuildServerSignaturePayload($data);
|
||||
|
||||
if (!$payload) {
|
||||
return new ServerSignatureVerification(false, null);
|
||||
}
|
||||
|
||||
$hash = $this->hasher->hash($payload->algorithm, $payload->verificationData);
|
||||
$expectedSignature = $this->hasher->hashHmacHex($payload->algorithm, $hash, $this->hmacKey);
|
||||
|
||||
parse_str($payload->verificationData, $params);
|
||||
|
||||
$verificationData = new ServerSignatureVerificationData(
|
||||
classification: isset($params['classification']) && \is_string($params['classification']) ? $params['classification'] : '',
|
||||
country: isset($params['country']) && \is_string($params['country']) ? $params['country'] : '',
|
||||
detectedLanguage: isset($params['detectedLanguage']) && \is_string($params['detectedLanguage']) ? $params['detectedLanguage'] : '',
|
||||
email: isset($params['email']) && \is_string($params['email']) ? $params['email'] : '',
|
||||
expire: isset($params['expire']) && is_numeric($params['expire']) ? (int) $params['expire'] : 0,
|
||||
fields: isset($params['fields']) && \is_array($params['fields']) ? $params['fields'] : [],
|
||||
fieldsHash: isset($params['fieldsHash']) && \is_string($params['fieldsHash']) ? $params['fieldsHash'] : '',
|
||||
reasons: isset($params['reasons']) && \is_array($params['reasons']) ? $params['reasons'] : [],
|
||||
score: isset($params['score']) && is_numeric($params['score']) ? (float) $params['score'] : 0.0,
|
||||
time: isset($params['time']) && is_numeric($params['time']) ? (int) $params['time'] : 0,
|
||||
verified: isset($params['verified']) && $params['verified'],
|
||||
);
|
||||
|
||||
$now = time();
|
||||
$isVerified = $payload->verified && $verificationData->verified
|
||||
&& $verificationData->expire > $now
|
||||
&& $payload->signature === $expectedSignature;
|
||||
|
||||
return new ServerSignatureVerification($isVerified, $verificationData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a solution to the given challenge.
|
||||
*
|
||||
* @param string $challenge The challenge hash.
|
||||
* @param string $salt The challenge salt.
|
||||
* @param Algorithm $algorithm Hashing algorithm.
|
||||
* @param int $max Maximum number to iterate to.
|
||||
* @param int $start Starting number.
|
||||
*/
|
||||
public function solveChallenge(string $challenge, string $salt, Algorithm $algorithm, int $max, int $start = 0): ?Solution
|
||||
{
|
||||
$startTime = microtime(true);
|
||||
|
||||
for ($n = $start; $n <= $max; $n++) {
|
||||
$hash = $this->hasher->hashHex($algorithm, $salt . $n);
|
||||
if ($hash === $challenge) {
|
||||
$took = microtime(true) - $startTime;
|
||||
|
||||
return new Solution($n, $took);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
|
||||
|
||||
/**
|
||||
* @phpstan-type ChallengeParams array<string, null|scalar>
|
||||
*/
|
||||
class BaseChallengeOptions
|
||||
{
|
||||
public const DEFAULT_MAX_NUMBER = 1000000;
|
||||
|
||||
public readonly string $salt;
|
||||
|
||||
/**
|
||||
* Options for creation of a new challenge.
|
||||
*
|
||||
* @see ChallengeOptions for options with sane defaults.
|
||||
*
|
||||
* @param ChallengeParams $params
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly Algorithm $algorithm,
|
||||
public readonly int $maxNumber,
|
||||
public readonly ?\DateTimeInterface $expires,
|
||||
string $salt,
|
||||
public readonly int $number,
|
||||
public readonly array $params,
|
||||
) {
|
||||
if ($expires) {
|
||||
$params['expires'] = $expires->getTimestamp();
|
||||
}
|
||||
|
||||
if (!empty($params)) {
|
||||
$salt .= '?' . http_build_query($params);
|
||||
}
|
||||
|
||||
// Add a delimiter to prevent parameter splicing
|
||||
if (!str_ends_with($salt, '&')) {
|
||||
$salt .= '&';
|
||||
}
|
||||
|
||||
$this->salt = $salt;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
class Challenge
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $algorithm,
|
||||
public readonly string $challenge,
|
||||
public readonly int $maxNumber,
|
||||
public readonly string $salt,
|
||||
public readonly string $signature,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
|
||||
|
||||
/**
|
||||
* @phpstan-import-type ChallengeParams from BaseChallengeOptions
|
||||
*/
|
||||
class ChallengeOptions extends BaseChallengeOptions
|
||||
{
|
||||
private const DEFAULT_SALT_LENGTH = 12;
|
||||
|
||||
/**
|
||||
* Options for creation of a new challenge with sane defaults.
|
||||
*
|
||||
* @param int $maxNumber Maximum number for the random number generator (default: 1,000,000)
|
||||
* @param Algorithm $algorithm Hashing algorithm to use (`SHA-1`, `SHA-256`, `SHA-512`, default:
|
||||
* `SHA-256`).
|
||||
* @param null|\DateTimeInterface $expires Optional expiration time for the challenge.
|
||||
* @param ChallengeParams $params Optional URL-encoded query parameters.
|
||||
* @param int<1, max> $saltLength Length of the random salt (default: 12 bytes).
|
||||
*/
|
||||
public function __construct(
|
||||
Algorithm $algorithm = Algorithm::SHA256,
|
||||
int $maxNumber = self::DEFAULT_MAX_NUMBER,
|
||||
?\DateTimeInterface $expires = null,
|
||||
array $params = [],
|
||||
int $saltLength = self::DEFAULT_SALT_LENGTH,
|
||||
) {
|
||||
parent::__construct(
|
||||
$algorithm,
|
||||
$maxNumber,
|
||||
$expires,
|
||||
bin2hex(self::randomBytes($saltLength)),
|
||||
self::randomInt($maxNumber),
|
||||
$params
|
||||
);
|
||||
}
|
||||
|
||||
private static function randomInt(int $max): int
|
||||
{
|
||||
return random_int(0, $max);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int<1, max> $length
|
||||
*/
|
||||
private static function randomBytes(int $length): string
|
||||
{
|
||||
return random_bytes($length);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
|
||||
|
||||
class CheckChallengeOptions extends BaseChallengeOptions
|
||||
{
|
||||
public function __construct(
|
||||
Algorithm $algorithm,
|
||||
string $salt,
|
||||
int $number,
|
||||
) {
|
||||
parent::__construct($algorithm, self::DEFAULT_MAX_NUMBER, null, $salt, $number, []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1\Hasher;
|
||||
|
||||
enum Algorithm: string
|
||||
{
|
||||
case SHA1 = 'SHA-1';
|
||||
case SHA256 = 'SHA-256';
|
||||
case SHA512 = 'SHA-512';
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1\Hasher;
|
||||
|
||||
class Hasher implements HasherInterface
|
||||
{
|
||||
public function hash(Algorithm $algorithm, string $data): string
|
||||
{
|
||||
return match ($algorithm) {
|
||||
Algorithm::SHA1 => sha1($data, true),
|
||||
Algorithm::SHA256 => hash('sha256', $data, true),
|
||||
Algorithm::SHA512 => hash('sha512', $data, true),
|
||||
};
|
||||
}
|
||||
|
||||
public function hashHex(Algorithm $algorithm, string $data): string
|
||||
{
|
||||
return bin2hex($this->hash($algorithm, $data));
|
||||
}
|
||||
|
||||
public function hashHmac(Algorithm $algorithm, string $data, string $hmacKey): string
|
||||
{
|
||||
return match ($algorithm) {
|
||||
Algorithm::SHA1 => hash_hmac('sha1', $data, $hmacKey, true),
|
||||
Algorithm::SHA256 => hash_hmac('sha256', $data, $hmacKey, true),
|
||||
Algorithm::SHA512 => hash_hmac('sha512', $data, $hmacKey, true),
|
||||
};
|
||||
}
|
||||
|
||||
public function hashHmacHex(Algorithm $algorithm, string $data, string $hmacKey): string
|
||||
{
|
||||
return bin2hex($this->hashHmac($algorithm, $data, $hmacKey));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1\Hasher;
|
||||
|
||||
interface HasherInterface
|
||||
{
|
||||
public function hash(Algorithm $algorithm, string $data): string;
|
||||
|
||||
public function hashHex(Algorithm $algorithm, string $data): string;
|
||||
|
||||
public function hashHmac(Algorithm $algorithm, string $data, string $hmacKey): string;
|
||||
|
||||
public function hashHmacHex(Algorithm $algorithm, string $data, string $hmacKey): string;
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Hasher;
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\HasherInterface;
|
||||
|
||||
class Obfuscator
|
||||
{
|
||||
public const DEFAULT_MAX_NUMBER = 10_000;
|
||||
|
||||
/**
|
||||
* @param int $maxNumber Maximum number for the random number generator (default: 10,000)
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly int $maxNumber = self::DEFAULT_MAX_NUMBER,
|
||||
private readonly HasherInterface $hasher = new Hasher(),
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypts a payload for PoW-based reveal using AES-GCM.
|
||||
*
|
||||
* @param string $raw Plaintext payload to encrypt.
|
||||
* @param string $key Symmetric key used to encrypt/decrypt the payload. Defaults to empty string, ie. no key.
|
||||
* @param null|int $counter Optional fixed PoW counter used to derive the IV. If null, a random integer in [0, $this->maxNumber] inclusive is chosen.
|
||||
*
|
||||
* @return string Base64-encoded bytes of ciphertext followed by the 16‑byte GCM authentication tag ($ciphertext . $tag).
|
||||
*/
|
||||
public function obfuscateData(string $raw, string $key = '', ?int $counter = null): string
|
||||
{
|
||||
$cipher = 'AES-256-GCM';
|
||||
$keyHash = $this->hasher->hash(Algorithm::SHA256, $key);
|
||||
|
||||
$ivLength = openssl_cipher_iv_length($cipher);
|
||||
|
||||
if (false === $ivLength) {
|
||||
throw new \RuntimeException('Getting cipher iv length failed.');
|
||||
}
|
||||
|
||||
$iv = ''; // AES‑GCM initialization vector (IV), typically 12 bytes for AES-256-GCM
|
||||
$num = $counter ?? $this->randomInt();
|
||||
|
||||
// Fill IV from the counter, one byte at a time (little‑endian)
|
||||
for ($i = 0; $i < $ivLength; $i++) {
|
||||
$iv .= \chr(abs($num % 256));
|
||||
$num = intdiv($num, 256);
|
||||
}
|
||||
|
||||
$encryptedData = openssl_encrypt($raw, $cipher, $keyHash, \OPENSSL_RAW_DATA, $iv, $tag);
|
||||
|
||||
if (!$encryptedData) {
|
||||
throw new \RuntimeException('Data encryption failed.');
|
||||
}
|
||||
|
||||
return base64_encode($encryptedData . $tag);
|
||||
}
|
||||
|
||||
private function randomInt(): int
|
||||
{
|
||||
return random_int(0, $this->maxNumber);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
|
||||
|
||||
class Payload
|
||||
{
|
||||
public function __construct(
|
||||
public readonly Algorithm $algorithm,
|
||||
public readonly string $challenge,
|
||||
public readonly int $number,
|
||||
public readonly string $salt,
|
||||
public readonly string $signature,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
|
||||
|
||||
class ServerSignaturePayload
|
||||
{
|
||||
public function __construct(
|
||||
public readonly Algorithm $algorithm,
|
||||
public readonly string $verificationData,
|
||||
public readonly string $signature,
|
||||
public readonly bool $verified,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
class ServerSignatureVerification
|
||||
{
|
||||
public function __construct(
|
||||
public readonly bool $verified,
|
||||
public readonly ?ServerSignatureVerificationData $data,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
class ServerSignatureVerificationData
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $fields
|
||||
* @param array<array-key, mixed> $reasons
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $classification,
|
||||
public readonly string $country,
|
||||
public readonly string $detectedLanguage,
|
||||
public readonly string $email,
|
||||
public readonly int $expire,
|
||||
public readonly array $fields,
|
||||
public readonly string $fieldsHash,
|
||||
public readonly array $reasons,
|
||||
public readonly float $score,
|
||||
public readonly int $time,
|
||||
public readonly bool $verified,
|
||||
) {
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha\V1;
|
||||
|
||||
class Solution
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $number,
|
||||
public readonly float $took,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\Http\HttpClientInterface;
|
||||
|
||||
class VerifyServerOptions
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed>|string $payload The payload to verify, as received from the client
|
||||
* (either the raw base64 string or a decoded array).
|
||||
* @param string $url Full URL of the Sentinel `/v1/verify/signature` endpoint.
|
||||
* @param null|string $secret API key secret. If provided, Sentinel checks that it
|
||||
* matches the API key associated with the payload.
|
||||
* @param null|HttpClientInterface $httpClient Custom HTTP client. Defaults to a built-in stream-based client.
|
||||
* @param array<string, string> $headers Additional headers to send with the request.
|
||||
* @param float $timeout Per-attempt request timeout in seconds. Defaults to `10.0`.
|
||||
* @param int $retries Number of retry attempts after the first try. Defaults to `0`.
|
||||
* @param int $retryDelay Base delay in milliseconds between retry attempts. Defaults to `300`.
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly array|string $payload,
|
||||
public readonly string $url,
|
||||
public readonly ?string $secret = null,
|
||||
public readonly ?HttpClientInterface $httpClient = null,
|
||||
public readonly array $headers = [],
|
||||
public readonly float $timeout = 10.0,
|
||||
public readonly int $retries = 0,
|
||||
public readonly int $retryDelay = 300,
|
||||
public readonly RetryBackoff $retryBackoff = RetryBackoff::Exponential,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
class VerifyServerResult
|
||||
{
|
||||
public function __construct(
|
||||
public readonly bool $verified,
|
||||
public readonly ?string $apiKey = null,
|
||||
public readonly ?string $reason = null,
|
||||
public readonly ?ServerSignatureVerificationData $verificationData = null,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $arr
|
||||
*/
|
||||
public static function fromArray(array $arr): self
|
||||
{
|
||||
/** @var null|array<string, mixed> $verificationData */
|
||||
$verificationData = isset($arr['verificationData']) && \is_array($arr['verificationData']) ? $arr['verificationData'] : null;
|
||||
|
||||
return new self(
|
||||
verified: isset($arr['verified']) && \is_bool($arr['verified']) && $arr['verified'],
|
||||
apiKey: isset($arr['apiKey']) && \is_string($arr['apiKey']) ? $arr['apiKey'] : null,
|
||||
reason: isset($arr['reason']) && \is_string($arr['reason']) ? $arr['reason'] : null,
|
||||
verificationData: null !== $verificationData ? new ServerSignatureVerificationData($verificationData) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
use HGCFVendor\AltchaOrg\Altcha\Algorithm\DeriveKeyInterface;
|
||||
|
||||
class VerifySolutionOptions
|
||||
{
|
||||
public readonly Payload $payload;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed>|Payload|string $payload A `Payload` object, a raw base64-encoded
|
||||
* payload string (as posted by the widget),
|
||||
* or an already-decoded associative array.
|
||||
*/
|
||||
public function __construct(
|
||||
Payload|string|array $payload,
|
||||
public readonly DeriveKeyInterface $algorithm,
|
||||
) {
|
||||
$this->payload = match (true) {
|
||||
$payload instanceof Payload => $payload,
|
||||
\is_string($payload) => Payload::fromBase64($payload),
|
||||
default => Payload::fromArray($payload),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace HGCFVendor\AltchaOrg\Altcha;
|
||||
|
||||
class VerifySolutionResult
|
||||
{
|
||||
public function __construct(
|
||||
public readonly bool $verified,
|
||||
public readonly bool $expired = false,
|
||||
public readonly ?bool $invalidSignature = null,
|
||||
public readonly ?bool $invalidSolution = null,
|
||||
public readonly float $time = 0.0,
|
||||
) {
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user