Add optional self-hosted ALTCHA protection and dependency maintenance

This commit is contained in:
parkel committed 2026-10-12 14:10:08 +02:00
1 parent 3b558409f3
commit 2a2f1d5878
59 files changed
+2648 -12

No files matched your search

+1
View File
@@ -42,6 +42,7 @@ function hgcf_admin_page() {
<section id="hgcf-general" class="hgcf-admin-panel"><div class="hgcf-admin-card"><h2>E-mail</h2><p>Dit zijn de standaardinstellingen voor alle workflows.</p><div class="hgcf-admin-grid">
<?php foreach(['recipient'=>['Ontvangstadres','email','Hier komen de formulierberichten binnen.'],'sender_email'=>['Afzenderadres','email','Gebruik een adres op een domein waarvoor je mailserver mag versturen. Leeg behoudt de standaard.'],'sender_name'=>['Afzendernaam','text','De naam die de ontvanger bij je mail ziet.'],'site_name'=>['Naam in e-mailonderwerp','text','Wordt vóór het onderwerp van de gekozen workflow geplaatst.'],'contact_name'=>['Contactnaam','text','Beschikbaar als {contact_name} in formulierteksten.']] as $key=>$field)hgcf_admin_input($field[0],'hgcf_settings['.$key.']',$s[$key],$field[1],$field[2]); ?>
</div><p class="hgcf-admin-note">Reply-To blijft het bezoekersadres. Het technische retouradres en de uiteindelijke aflevering worden door de mailvoorziening bepaald.</p></div>
<div class="hgcf-admin-card"><h2>Antispam</h2><input type="hidden" name="hgcf_settings[altcha_enabled]" value="0"><label class="hgcf-checkbox"><input type="checkbox" name="hgcf_settings[altcha_enabled]" value="1" <?php checked($s['altcha_enabled']); ?>> Antispamcontrole inschakelen (ALTCHA)</label><p>Gratis, lokaal en zonder account of API-sleutels. De browser voert een korte controle uit voordat een bericht kan worden verstuurd. De bestaande honeypot en verzendlimiet blijven actief.</p><p class="description">JavaScript is hiervoor nodig. Scripts en verificatie blijven op deze website; er wordt geen externe dienst aangeroepen.</p></div>
<div class="hgcf-admin-card"><h2>Op een pagina plaatsen</h2><p>Plaats <code>[hg_contactform]</code> in een shortcodeblok. De taal volgt de website<?php if(count($languages)>1)echo ' en Polylang'; ?>.</p><p>Naam, e-mailadres, bericht en toestemming vormen de basis. Via Workflows geef je bezoekers aanvullende routes, zoals een vraag of een afspraakaanvraag.</p></div></section>
<section id="hgcf-workflows" class="hgcf-admin-panel"><div class="hgcf-panel-heading"><div><h2>Workflows</h2><p>Eén workflow is één keuze voor de bezoeker. Klap een kaart open om de velden aan te passen.</p></div><button type="button" class="button button-secondary" id="hgcf-add-workflow">Workflow toevoegen</button></div>
<div id="hgcf-workflow-list" data-next-index="<?php echo count($flows); ?>"><?php $i=0;foreach($flows as $flow)hgcf_workflow_card($flow,$i++,$languages); ?></div>
+88
View File
@@ -0,0 +1,88 @@
<?php
if (!defined('ABSPATH')) exit;
spl_autoload_register(function ($class) {
$prefix = 'HGCFVendor\\AltchaOrg\\Altcha\\';
if (!str_starts_with($class, $prefix)) return;
$relative = substr($class, strlen($prefix));
if (!preg_match('/^[A-Za-z0-9_\\\\]+$/D', $relative)) return;
$file = __DIR__.'/vendor/altcha/src/'.str_replace('\\', '/', $relative).'.php';
if (is_file($file)) require_once $file;
});
function hgcf_altcha_enabled() { return hgcf_setting('altcha_enabled') === true; }
function hgcf_altcha_engine() {
return new HGCFVendor\AltchaOrg\Altcha\Altcha(hash_hmac('sha256', 'hgcf-altcha-v1|'.home_url('/'), wp_salt('auth')));
}
function hgcf_create_altcha_challenge($page) {
return hgcf_altcha_engine()->createChallenge(new HGCFVendor\AltchaOrg\Altcha\CreateChallengeOptions(
algorithm: new HGCFVendor\AltchaOrg\Altcha\Algorithm\Pbkdf2(),
cost: 1000, keyPrefix: '00', expiresAt: time()+20*MINUTE_IN_SECONDS,
data: ['page'=>(int)$page]
))->toArray();
}
/** Validate before derivation, then atomically claim a single-use answer. */
function hgcf_verify_altcha($raw, $page) {
if (!is_string($raw) || $raw === '' || strlen($raw)>8192) return false;
$decoded = base64_decode($raw, true);
if ($decoded === false) return false;
$payload = json_decode($decoded, true, 12);
if (!is_array($payload) || !is_array($payload['challenge']??null) || !is_array($payload['solution']??null)) return false;
$challenge=$payload['challenge']; $p=$challenge['parameters']??null; $s=$payload['solution'];
if (!is_array($p) || ($p['algorithm']??'')!=='PBKDF2/SHA-256' || ($p['cost']??null)!==1000 || ($p['keyLength']??null)!==32 || ($p['keyPrefix']??'')!=='00') return false;
if (isset($p['keySignature']) || isset($p['memoryCost']) || isset($p['parallelism'])) return false;
if (!is_array($p['data']??null) || ($p['data']['page']??null)!==(int)$page) return false;
$expires=$p['expiresAt']??null;
if (!is_int($expires) || $expires<=time() || $expires>time()+20*MINUTE_IN_SECONDS) return false;
foreach (['nonce','salt'] as $key) if (!is_string($p[$key]??null) || !preg_match('/^[a-f0-9]{32}$/D',$p[$key])) return false;
if (!is_string($challenge['signature']??null) || !preg_match('/^[a-f0-9]{64}$/D',$challenge['signature'])) return false;
if (!is_int($s['counter']??null) || $s['counter']<0 || $s['counter']>1000000 || !is_string($s['derivedKey']??null) || !preg_match('/^[a-f0-9]{64}$/D',$s['derivedKey'])) return false;
try {
$result=hgcf_altcha_engine()->verifySolution(new HGCFVendor\AltchaOrg\Altcha\VerifySolutionOptions(
payload: $payload, algorithm: new HGCFVendor\AltchaOrg\Altcha\Algorithm\Pbkdf2()
));
if (!$result->verified) return false;
} catch (Throwable $error) { return false; }
// Unique option_name index prevents simultaneous replays. No form data is stored.
return add_option('hgcf_pow_used_'.hash('sha256',$challenge['signature']), $expires, '', false);
}
function hgcf_altcha_cleanup() {
global $wpdb;
$keys=$wpdb->get_col($wpdb->prepare("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND CAST(option_value AS UNSIGNED) < %d LIMIT 1000", $wpdb->esc_like('hgcf_pow_used_').'%', time()));
foreach($keys as $key)delete_option($key);
if(!hgcf_altcha_enabled()&&!$keys)wp_clear_scheduled_hook('hgcf_altcha_cleanup');
}
add_action('hgcf_altcha_cleanup','hgcf_altcha_cleanup');
function hgcf_altcha_schedule() {
if (hgcf_altcha_enabled()) {
if (!wp_next_scheduled('hgcf_altcha_cleanup')) wp_schedule_event(time()+HOUR_IN_SECONDS,'hourly','hgcf_altcha_cleanup');
}
}
add_action('init','hgcf_altcha_schedule');
register_deactivation_hook(HGCF_FILE, function(){wp_clear_scheduled_hook('hgcf_altcha_cleanup');hgcf_altcha_cleanup();});
function hgcf_altcha_endpoint($request) {
if (!hgcf_altcha_enabled()) return new WP_Error('hgcf_disabled','Not found.',['status'=>404]);
$page=(int)$request->get_param('page'); $post=get_post($page);
if (!$post || !is_post_publicly_viewable($post) || (!has_shortcode($post->post_content,'hg_contactform') && !has_shortcode($post->post_content,'mlh_contact'))) return new WP_Error('hgcf_page','Invalid form page.',['status'=>404]);
$key='hgcf_pow_rate_'.hash_hmac('sha256',$_SERVER['REMOTE_ADDR']??'unknown',wp_salt('auth'));
$rate=get_transient($key);
if ($rate && $rate['count']>=30) return new WP_Error('hgcf_rate','Please try again in a few minutes.',['status'=>429]);
$rate=$rate?:['count'=>0,'until'=>time()+5*MINUTE_IN_SECONDS]; $rate['count']++;
set_transient($key,$rate,max(1,$rate['until']-time()));
try { return new WP_REST_Response(hgcf_create_altcha_challenge($page),200,['Cache-Control'=>'no-store, private, max-age=0']); }
catch (Throwable $error) { return new WP_Error('hgcf_unavailable','Verification temporarily unavailable.',['status'=>503]); }
}
add_action('rest_api_init',function(){
register_rest_route('hg-contactform/v1','/challenge',[
'methods'=>'GET','callback'=>'hgcf_altcha_endpoint','permission_callback'=>'__return_true',
'args'=>['page'=>['required'=>true,'type'=>'integer','minimum'=>1]]
]);
});
add_filter('rest_post_dispatch',function($response,$server,$request){
if ($request->get_route()==='/hg-contactform/v1/challenge' && $response instanceof WP_REST_Response) $response->header('Cache-Control','no-store, private, max-age=0');
return $response;
},10,3);
add_filter('script_loader_tag',function($tag,$handle){
if ($handle!=='hgcf-altcha') return $tag;
$tag=preg_replace('/\s+type=([\'"])text\/javascript\1/','',$tag);
return str_replace('<script ', '<script type="module" ', $tag);
},10,2);
+4 -1
View File
@@ -62,9 +62,12 @@ function hgcf_render($atts=[]) {
<div class="form-fields"><?php if($has('date')): ?><label for="mlhc-date" data-hgcf-field="date"><span data-hgcf-label><?php echo esc_html($t('Voorkeursdatum','Preferred date')); ?></span><input id="mlhc-date" name="mlhc_preferred_date" type="date" min="<?php echo esc_attr(wp_date('Y-m-d')); ?>" value="<?php echo esc_attr($value('preferred_date')); ?>"></label><?php endif; ?><?php if($has('time')): ?><label for="mlhc-time" data-hgcf-field="time"><span data-hgcf-label><?php echo esc_html($t('Voorkeurstijd','Preferred time')); ?></span><input id="mlhc-time" name="mlhc_preferred_time" type="time" min="<?php echo esc_attr($flow['opening_time']); ?>" max="<?php echo esc_attr($flow['closing_time']); ?>" value="<?php echo esc_attr($value('preferred_time')); ?>"></label><?php endif; ?></div>
</fieldset><?php endif; ?><p class="form-note workflow-hint"><?php echo esc_html(hgcf_translated($flow['hint'],$lang)); ?></p>
<label for="mlhc-message"><span class="message-label"><?php echo esc_html(hgcf_translated($flow['message_label'],$lang)); ?></span><textarea id="mlhc-message" name="mlhc_message" rows="5" maxlength="5000"><?php echo esc_textarea($value('message')); ?></textarea></label>
<label class="consent"><input type="checkbox" name="mlhc_consent" value="1" required <?php checked($value('consent'),'1'); ?>><span><?php echo esc_html(hgcf_local_setting('consent',$lang)); ?></span></label><p class="form-note"><?php echo esc_html(hgcf_local_setting('note',$lang)); ?></p><button type="submit" class="button"><?php echo esc_html($t('Verstuur bericht','Send message')); ?></button>
<label class="consent"><input type="checkbox" name="mlhc_consent" value="1" required <?php checked($value('consent'),'1'); ?>><span><?php echo esc_html(hgcf_local_setting('consent',$lang)); ?></span></label><p class="form-note"><?php echo esc_html(hgcf_local_setting('note',$lang)); ?></p>
<?php if(hgcf_altcha_enabled()): ?><div class="hgcf-antispam"><altcha-widget name="mlhc_altcha" challenge="<?php echo esc_url(add_query_arg('page',get_queried_object_id(),rest_url('hg-contactform/v1/challenge'))); ?>" language="<?php echo esc_attr(substr($lang,0,2)); ?>" auto="onfocus" workers="2"></altcha-widget><noscript><p class="form-note"><?php echo esc_html($t('Schakel JavaScript in voor de antispamcontrole of gebruik een andere contactmogelijkheid.','Enable JavaScript for the spam protection check or use another contact option.')); ?></p></noscript></div><?php endif; ?>
<button type="submit" class="button"><?php echo esc_html($t('Verstuur bericht','Send message')); ?></button>
</form></section>
<?php
if(hgcf_altcha_enabled())wp_enqueue_script('hgcf-altcha',plugins_url('assets/vendor/altcha/widget.js',HGCF_FILE),[],HGCF_VERSION,true);
wp_enqueue_style('hgcf',plugins_url('assets/contact.css',HGCF_FILE),[],HGCF_VERSION);wp_enqueue_script('hgcf',plugins_url('assets/contact.js',HGCF_FILE),[],HGCF_VERSION,true);
return ob_get_clean();
}
+5 -1
View File
@@ -1,7 +1,7 @@
<?php
if (!defined('ABSPATH')) exit;
function hgcf_defaults() {
return ['recipient'=>get_option('admin_email'),'site_name'=>get_bloginfo('name'),'contact_name'=>'','sender_email'=>'','sender_name'=>'',
return ['recipient'=>get_option('admin_email'),'site_name'=>get_bloginfo('name'),'contact_name'=>'','sender_email'=>'','sender_name'=>'','altcha_enabled'=>false,
'title_nl'=>'Waarmee kunnen we je helpen?','title_en'=>'How can we help?',
'consent_nl'=>'Mijn gegevens mogen worden gebruikt om op dit bericht te reageren.','consent_en'=>'My details may be used to reply to this message.',
'note_nl'=>'Je bericht wordt per e-mail verstuurd en niet op deze website opgeslagen. Deel hier geen medische of andere gevoelige gegevens.','note_en'=>'Your message is sent by email and is not stored on this website. Please do not include medical or other sensitive details.',
@@ -86,6 +86,10 @@ function hgcf_sanitize_settings($input) {
$old=hgcf_settings();if(!is_array($input))return $old;
if(($_POST['option_page']??'')==='hgcf'&&($input['_complete']??'')!=='1'){add_settings_error('hgcf_settings','incomplete','Niet alle velden zijn ontvangen. Je instellingen zijn niet gewijzigd.');return $old;}
$out=$old;
if(array_key_exists('altcha_enabled',$input)) {
if(in_array($input['altcha_enabled'],['0','1'],true))$out['altcha_enabled']=$input['altcha_enabled']==='1';
else add_settings_error('hgcf_settings','altcha_enabled','Controleer de antispaminstelling.');
}
foreach(['recipient'=>false,'sender_email'=>true] as $key=>$empty){if(array_key_exists($key,$input)){if(hgcf_valid_email($input[$key],$empty))$out[$key]=$input[$key]===''?'':sanitize_email($input[$key]);else add_settings_error('hgcf_settings',$key,'Controleer het e-mailadres.');}}
foreach(['sender_name','site_name','contact_name'] as $key)if(array_key_exists($key,$input)) {
$value=$input[$key];if(is_string($value)&&strlen($value)<=150&&!preg_match('/[\r\n]/',$value)&&($key!=='site_name'||trim($value)!==''))$out[$key]=sanitize_text_field($value);else add_settings_error('hgcf_settings',$key,'Controleer de naam.');
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Daniel Regeci
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+37
View File
@@ -0,0 +1,37 @@
{
"name": "altcha-org/altcha",
"description": "A lightweight PHP library for creating and verifying ALTCHA challenges.",
"type": "library",
"license": "MIT",
"autoload": {
"psr-4": {
"AltchaOrg\\Altcha\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"AltchaOrg\\Altcha\\Tests\\": "tests/"
}
},
"authors": [
{
"name": "Daniel Regeci",
"email": "536331+ovx@users.noreply.github.com"
}
],
"require": {
"php": ">=8.1"
},
"require-dev": {
"phpunit/phpunit": "^10.5 || ^11.5",
"phpstan/phpstan": "^2.1",
"phpstan/phpstan-phpunit": "^2.0",
"phpstan/extension-installer": "^1.4",
"friendsofphp/php-cs-fixer": "^3.72"
},
"config": {
"allow-plugins": {
"phpstan/extension-installer": true
}
}
}
+38
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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);
}
}
+21
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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,
);
}
}
+32
View File
@@ -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
View File
@@ -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',
};
}
}
+11
View File
@@ -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;
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Http;
class HttpResponse
{
public function __construct(
public readonly int $statusCode,
public readonly string $body,
) {
}
}
+64
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -0,0 +1,9 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
enum RetryBackoff
{
case Fixed;
case Exponential;
}
+73
View File
@@ -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
View File
@@ -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
View File
@@ -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,
);
}
}
+17
View File
@@ -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
View File
@@ -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;
}
}
+46
View File
@@ -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
View File
@@ -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,
) {
}
}
+53
View File
@@ -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);
}
}
+16
View File
@@ -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, []);
}
}
+10
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -0,0 +1,12 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
class Solution
{
public function __construct(
public readonly int $number,
public readonly float $took,
) {
}
}
+33
View File
@@ -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,
) {
}
}
+30
View File
@@ -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,
);
}
}
+26
View File
@@ -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),
};
}
}
+15
View File
@@ -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,
) {
}
}
+61
View File
@@ -0,0 +1,61 @@
{
"widget": {
"version": "3.3.0",
"source": "https://registry.npmjs.org/altcha/-/altcha-3.3.0.tgz",
"integrity": "sha512-olIeb1A5K2wzbFSxV3qgeknygbdJt7qmzCfAZn704PWsE9iGrfc/oTw1FfiESjsvaJf8Uk6elJX8opKq5u7dTw=="
},
"php": {
"version": "2.3.0",
"source": "https://api.github.com/repos/altcha-org/altcha-lib-php/tarball/v2.3.0",
"archive_sha256": "3502eaaf884a04174324b432aaf2a3b7e98275a8482516e1ae6b4ab9c22343ec",
"namespace": "HGCFVendor\\AltchaOrg\\Altcha"
},
"files_sha256": {
"assets/vendor/altcha/LICENSE.txt": "bee1fb9d9c97d42c12c22332c5250f2fb1ef5c2321f6f82beb23e3b77be50a29",
"assets/vendor/altcha/widget.js": "6274613eb63f019f256327a371155710f17b1ff7d2b5cfcc8b8fa50e8dc056bc",
"includes/vendor/altcha/LICENSE.txt": "acf2b86dd7e2f5810c27d2f1c83a5bb4677d56b95249988586014fb2e818a695",
"includes/vendor/altcha/composer.json": "a915f93614e96ce4e62429a04fe7081e58f837606cf126fff1a41d19fafb8785",
"includes/vendor/altcha/src/Algorithm/Argon2id.php": "e407af4b7072764dc144e8636d765be18f3e1ee2a93b5e77d7df872c5867df65",
"includes/vendor/altcha/src/Algorithm/DeriveKeyInterface.php": "8b445c280607c9f1fdd9539308f1916c69c0024d63bc1b82a005c0171b403563",
"includes/vendor/altcha/src/Algorithm/DeriveKeyResult.php": "64a4a51fd52a5607f201a2d6cbf51c335dafdf3587be95a0f6d8cb67a7797afb",
"includes/vendor/altcha/src/Algorithm/Pbkdf2.php": "7220244a80e4689bdb0a3e0cb2dd35055e774e2c37257d85d081f05cf225cda8",
"includes/vendor/altcha/src/Algorithm/Scrypt.php": "7b19487042fcb30d0bbfbb44f535c535a041883f4a12a78730b5195eace6410f",
"includes/vendor/altcha/src/Algorithm/Sha.php": "c5f189334d1c784293507d9d7d92c42d3955a7b735e6f825c3f43310599af289",
"includes/vendor/altcha/src/Algorithm/ShaAlgorithm.php": "79355cd8e87a91eb6389896f29451e7e7a5a064f393185a39c22de44dec9af52",
"includes/vendor/altcha/src/Altcha.php": "635aba69ebb2a07c02729ed8af270370f0f0b52636d20561a0ee0ff5aeeabf53",
"includes/vendor/altcha/src/Challenge.php": "609343cce82d5305cd9c1c382b7f183f7b7888c68dc5975fccc09343cee2dec2",
"includes/vendor/altcha/src/ChallengeParameters.php": "fd439cf48246e587ff7ae70a010ee59c97d894d1f98fc6121d3e33125b51fee1",
"includes/vendor/altcha/src/CreateChallengeOptions.php": "3bccaea255abf5d75b2c5638f5e5830aad539c176c500e15ce916d7825795599",
"includes/vendor/altcha/src/HmacAlgorithm.php": "20154f3100275a6a0bdf9626d6b5e05590ca8486299f5f0fe2fafd257594403a",
"includes/vendor/altcha/src/Http/HttpClientInterface.php": "7f08599a4d842e197abb5d013fc3dade4328b6b21afc7d43d742ad810e9839a6",
"includes/vendor/altcha/src/Http/HttpResponse.php": "bdb407dda438d8c32465adf12d52d06be3646b8a5485297a26bcee7a8a7be47b",
"includes/vendor/altcha/src/Http/StreamHttpClient.php": "d985310e23f150eec2a8f57dd5d0e6e6f153c1faf1f1c56e16341ca424877cad",
"includes/vendor/altcha/src/Obfuscator.php": "9ddb78f1fbc98329abca53991b1969f53cc8eb81fa9d4463d3d61a4219566ca4",
"includes/vendor/altcha/src/Payload.php": "aaadea995193cd2ac5531343405c1e32cf501e2e943e330891b766b371cf959c",
"includes/vendor/altcha/src/RetryBackoff.php": "efe00dcf4bfb5fed52a9475009541fcd7c6f3f3c88f2054b8b31430206c61471",
"includes/vendor/altcha/src/Sentinel.php": "011f64a88f5268cf52aeff28376f31bbb0fbd95eacaba72fd217e5bb9cffc6ae",
"includes/vendor/altcha/src/ServerSignature.php": "4ae057926022703e8d33763125554fc031572f9983314039cb563620976a0d73",
"includes/vendor/altcha/src/ServerSignatureVerification.php": "1a95b0b24d967dd069a208b7215c041be64b7828838bd2b2da3361119a801050",
"includes/vendor/altcha/src/ServerSignatureVerificationData.php": "363ae141dcdbec12a13c6d7bc4c3ca28ae8cdf583853057e9d8888ca6070febe",
"includes/vendor/altcha/src/Solution.php": "637b1195cb573eccc67cc392d215af4c82dc1f0ec169f8e2bd040ec17d0b010f",
"includes/vendor/altcha/src/SolveChallengeOptions.php": "1d6a728e6f04f7058fa3e0320a3ba2c2b28eeb6097e32b7fd10c4ba514a1d3bc",
"includes/vendor/altcha/src/V1/Altcha.php": "470dad3632f5bb2ef857a168b32407ac63308be4e759a725e946aa07e803b880",
"includes/vendor/altcha/src/V1/BaseChallengeOptions.php": "9fa61ab32a62af89ab7cb0e7623fe1bf3ea1ffe82a23fe0a325f25647eb68a39",
"includes/vendor/altcha/src/V1/Challenge.php": "c5704fea061441c012d4aa837136a5acb15ae579346aa7ee46fedae8a3284a86",
"includes/vendor/altcha/src/V1/ChallengeOptions.php": "b295d10301476b04a946396e9a02b72c20fcddacbae894afbb472862cf2530c8",
"includes/vendor/altcha/src/V1/CheckChallengeOptions.php": "f869a628f66e859922d23fc119a3fb04fdcff8dc7ed2603d0d37eff229a443f1",
"includes/vendor/altcha/src/V1/Hasher/Algorithm.php": "e1bc0d28c3e7f0a1e00e0b5f551ffad924094a1d464df3b1e04eb57e3acb9fb7",
"includes/vendor/altcha/src/V1/Hasher/Hasher.php": "be03a781c72c7e40d4c80d061631fb97d59ca2e53e74371d7ab905918352332d",
"includes/vendor/altcha/src/V1/Hasher/HasherInterface.php": "1f5d6a64019dca688d5751b69395ae3fe705fbe4410ad172ebf88057cb4c6a12",
"includes/vendor/altcha/src/V1/Obfuscator.php": "b24d07a7156de21d1627299aa1e2003784301aa8a7b4721433c8e1c7b33becd5",
"includes/vendor/altcha/src/V1/Payload.php": "2d049bb73b5c24718e6ef431dcca41e027be0a3ddc84c804458bca0bc339802f",
"includes/vendor/altcha/src/V1/ServerSignaturePayload.php": "595d5875d3f40df21d4b5c4cebdad1e57bc58184232aa1c84fd478802f343256",
"includes/vendor/altcha/src/V1/ServerSignatureVerification.php": "b0349710a68dc4c83136d4b9a97b3ed59a0ce9abe41758f5621aef4ca1d04035",
"includes/vendor/altcha/src/V1/ServerSignatureVerificationData.php": "1a5370c6dfadbcf9afc3e681ae34c14b7224c91263e91133b947516ddb24661d",
"includes/vendor/altcha/src/V1/Solution.php": "6496aaaacab8daf98bdbb21267ad7f37f9f0780db94ec3eee709c03b1a3c0ec8",
"includes/vendor/altcha/src/VerifyServerOptions.php": "7f108d0a5075786d84a0624214b98a7462a7bf0bad136a29d5b5d486be5f3c8d",
"includes/vendor/altcha/src/VerifyServerResult.php": "1445552daab68d643b95f22a688fc4a39f0b27832c57be6f46b144c6006ff685",
"includes/vendor/altcha/src/VerifySolutionOptions.php": "4ca88774e3e5e44bda93bae728dc77ff61fab06ed24b4f9ae526571bc7873523",
"includes/vendor/altcha/src/VerifySolutionResult.php": "36d1a9c67b6325f5fee79e82f0a69fb088374dff5babebac2dee749728a0d769"
}
}