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
@@ -28,6 +28,28 @@ Bestaande vraag- en aanvraaginstellingen worden automatisch naar workflows verta
|
||||
|
||||
Instellingen worden opgeslagen via de WordPress Settings API en zijn alleen te wijzigen door gebruikers met `manage_options`. Ongeldige e-mailadressen, tijdsbereiken en dienstenlijsten behouden de vorige geldige waarde.
|
||||
|
||||
## Antispam
|
||||
|
||||
Onder **Algemeen → Antispam** kun je ALTCHA met één vinkje inschakelen. Nieuwe installaties beginnen met de bestaande basisbescherming; ALTCHA is optioneel. Er zijn geen API-sleutels, accounts, betaalde abonnementen of wijzigingen aan de hosting nodig. PHP 8.1+ en een moderne browser met JavaScript en HTTPS (Web Crypto) zijn vereist. De lokale widget volgt de formuliertaal. Zonder JavaScript toont het formulier een verwijzing naar andere contactmogelijkheden en wordt verzending met ingeschakelde ALTCHA geweigerd.
|
||||
|
||||
De plugin bundelt ALTCHA-widget 3.3.0 en PHP-library 2.3.0 (MIT), inclusief licenties en een privé-namespace voor de PHP-library om conflicten met andere plugins te vermijden. Alle runtime-assets en controles blijven op de eigen website. De standaard PBKDF2-uitdaging verloopt na twintig minuten en is gebonden aan de formulierpagina. Geldige oplossingen worden vóór verzending atomair als gebruikt vastgelegd; hergebruik wordt geweigerd. Alleen een hash en vervaltijd worden opgeslagen, geen formuliergegevens. WordPress Cron ruimt verlopen records periodiek op zolang de plugin actief is. Het challenge-endpoint levert niet-cachebare antwoorden en begrenst aanvragen per gehashte IP-identificatie tot dertig per vijf minuten. De bestaande honeypot, tijdcontrole en verzendlimiet blijven actief. Dit is een extra drempel voor bots, geen garantie dat een bezoeker een mens is.
|
||||
|
||||
## ALTCHA bijwerken
|
||||
|
||||
Versies, officiële downloadbronnen en hashes staan in `includes/vendor/altcha/versions.json`. Er zijn geen automatische dependency-updates op websites. Controleer bij pluginonderhoud en bij beveiligingsmeldingen of een nieuwe upstreamversie beschikbaar is:
|
||||
|
||||
```sh
|
||||
python3 scripts/update_altcha.py --check
|
||||
```
|
||||
|
||||
Lees de upstream changelogs, kies expliciete versies en werk de lokale bestanden bij:
|
||||
|
||||
```sh
|
||||
python3 scripts/update_altcha.py --widget-version 3.3.0 --php-version 2.3.0
|
||||
```
|
||||
|
||||
Het script controleert de NPM-integrity, bewaart licenties en legt hashes vast. De PHP-archive komt via HTTPS uit de officiële GitHub-release; de vastgelegde SHA-256 is een reproduceerbaarheidscontrole, geen onafhankelijke handtekening. De PHP-namespace wordt bij het bundelen automatisch geïsoleerd. Controleer de diff, voer de beveiligings- en browsertests uit, verhoog de pluginversie en maak een nieuwe ZIP. Rol eerst uit op een testsite en daarna per klantwebsite. Het script installeert of deployt niets op servers. Automatische WordPress-updates vanuit deze Git-repo zijn nog niet ingericht.
|
||||
|
||||
## Gedrag en beheer
|
||||
|
||||
Berichten worden met `wp_mail()` verstuurd, niet als inzendingen opgeslagen. De bestaande mailvoorziening bepaalt aflevering; de plugin configureert geen SMTP. Gebruik geen gevoelige medische gegevens in dit formulier. Antispam bestaat uit noncecontrole, honeypot, een getekend tijdstip en een limiet per gehashte IP-identificatie. Tijdelijke rate-limitgegevens blijven maximaal vijftien minuten na de laatste poging bestaan. Cache pagina’s met het formulier niet langdurig: nonces en tijdstempels verlopen.
|
||||
@@ -40,9 +62,10 @@ Een aanvraag is pas een afspraak na bevestiging. Er is geen agenda, beschikbaarh
|
||||
|
||||
```sh
|
||||
wp eval-file /pad/naar/hg_contactform/tests/integration.php
|
||||
wp eval-file /pad/naar/hg_contactform/tests/antispam.php
|
||||
```
|
||||
|
||||
De checks injecteren tijdelijke instellingen via filters, onderscheppen e-mail en schrijven geen formulierinzendingen of permanente testinstellingen. PHP-syntax kan met `php -l` worden gecontroleerd. Test echte mailaflevering apart met een expliciet afgesproken testadres.
|
||||
De checks injecteren tijdelijke instellingen via filters en onderscheppen e-mail. De ALTCHA-checks gebruiken en verwijderen eigen tijdelijke replay- en limietrecords; er worden geen formulierinzendingen of permanente testinstellingen opgeslagen. De testsite moet een gepubliceerde pagina met het formulier bevatten. `tests/browser.cjs` controleert de echte widget, taal, workflowkeuze en POST-validatie met Playwright; geldige verzendingen worden in de browser onderschept voordat ze de server bereiken. PHP-syntax kan met `php -l` worden gecontroleerd. Test echte mailaflevering apart met een expliciet afgesproken testadres.
|
||||
|
||||
## Uitrollen
|
||||
|
||||
|
||||
@@ -2,3 +2,5 @@
|
||||
.contact-form{margin-top:40px;padding:30px;background:#fff;border:1px solid var(--line);border-radius:12px;max-width:850px}.contact-form h2{font-size:1.8rem}.mlhc-form label{display:block;font-size:14px;font-weight:600;margin:0 0 18px}.mlhc-form input:not([type=radio]):not([type=checkbox]):not([type=hidden]),.mlhc-form select,.mlhc-form textarea{display:block;width:100%;border:1px solid #ad98a1;border-radius:5px;padding:11px 12px;margin:7px 0 0;font:400 16px/1.5 system-ui,sans-serif;color:var(--ink);background:#fcf9f6}.mlhc-form input:focus-visible,.mlhc-form select:focus-visible,.mlhc-form textarea:focus-visible{outline:2px solid var(--rose);outline-offset:2px}.mlhc-form fieldset{border:0;margin:0 0 20px;padding:0}.mlhc-form legend{font-size:14px;font-weight:600;margin-bottom:12px}.form-mode{display:flex;flex-wrap:wrap;gap:12px 25px}.form-mode label{font-weight:400;margin:0;display:flex;gap:9px;align-items:center}.mlhc-form input[type=radio],.mlhc-form input[type=checkbox]{accent-color:var(--rose);width:18px;height:18px;flex-shrink:0}.form-fields{display:grid;grid-template-columns:1fr 1fr;gap:18px}.request-fields{background:var(--cream);padding:18px!important;border-radius:8px}.request-fields[hidden]{display:none}.mlhc-form .consent{display:flex;gap:10px;align-items:start;font-weight:400}.form-note{font-size:12px;color:var(--muted);line-height:1.6}.mlhc-form button{border:0;cursor:pointer}.mlhc-form button:disabled{opacity:.7;cursor:wait}.mlhc-trap{position:absolute;left:-10000px;width:1px;height:1px;overflow:hidden}.form-errors{border:1px solid var(--rose);background:#fff0f5;border-radius:6px;padding:18px;margin-bottom:22px;font-size:14px}.form-errors p{margin-bottom:8px}.form-errors ul{margin:0;padding-left:20px}.form-success{border-color:#497653}.form-success h2{color:#315a3a}
|
||||
|
||||
@media(max-width:540px){.hgcf-contact .form-fields{grid-template-columns:1fr;gap:0}.hgcf-contact{padding:20px}}
|
||||
|
||||
.hgcf-antispam{margin:18px 0 22px;max-width:100%}.hgcf-antispam altcha-widget{display:block;--altcha-color-primary:var(--rose);--altcha-border-color:var(--line);--altcha-color-base-content:var(--ink);--altcha-border-radius:6px;--altcha-max-width:100%}
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
const hint=form.querySelector('.workflow-hint');hint.textContent=flow.hint;hint.hidden=!flow.hint;
|
||||
}
|
||||
form.querySelectorAll('[name="mlhc_mode"]').forEach(input=>input.addEventListener('change',update));update();
|
||||
form.addEventListener('submit',()=>{const button=form.querySelector('[type="submit"]');button.disabled=true;button.textContent=form.dataset.hgcfSending;});
|
||||
form.addEventListener('submit',event=>{const widget=form.querySelector('altcha-widget');if(widget&&!form.querySelector('input[name="mlhc_altcha"]')?.value){event.preventDefault();widget.focus();return;}if(event.defaultPrevented)return;const button=form.querySelector('[type="submit"]');button.disabled=true;button.textContent=form.dataset.hgcfSending;});
|
||||
});
|
||||
const errors=document.querySelector('.form-errors');if(errors)errors.focus();
|
||||
})();
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023-2026 Daniel Regeci, BAU Software s.r.o.
|
||||
|
||||
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.
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
const e=!1;var t=Array.isArray,n=Array.prototype.indexOf,a=Array.prototype.includes,r=Array.from,i=Object.keys,o=Object.defineProperty,l=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyDescriptors,c=Object.prototype,d=Array.prototype,u=Object.getPrototypeOf,f=Object.isExtensible;const h=()=>{};function g(){var e,t;return{promise:new Promise((n,a)=>{e=n,t=a}),resolve:e,reject:t}}const v=1<<24,p=16,b=32,m=64,y=512,k=1024,w=2048,A=4096,x=8192,C=16384,_=32768,$=1<<25,L=65536,S=1<<17,T=1<<19,j=65536,E=1<<21,P=1<<23,z=Symbol("$state"),I=Symbol("component"),V=Symbol("legacy props"),R=Symbol(""),H=Symbol("attributes"),O=Symbol("class"),F=Symbol("style"),M=Symbol("text"),N=Symbol("form reset"),q=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"},U=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");function D(e){return e===this.v}function B(e,t){return e!=e?t==t:e!==t||null!==e&&"object"==typeof e||"function"==typeof e}function K(e){return!B(e,this.v)}const G={},W=Symbol("uninitialized"),Y="http://www.w3.org/1999/xhtml";let Z=null;function J(e){Z=e}function X(e,t=!1,n){Z={p:Z,i:!1,c:null,e:null,s:e,x:null,r:qt,l:null}}function Q(e){var t=Z,n=t.e;if(null!==n)for(var a of(t.e=null,n))mn(a);return void 0!==e&&(t.x=e),t.i=!0,Z=t.p,ee(e)}function ee(e={}){return o(e,I,{value:!0}),e}let te=[];function ne(){var e=te;te=[],function(e){for(var t=0;t<e.length;t++)e[t]()}(e)}function ae(e){if(0===te.length&&!ut){var t=te;queueMicrotask(()=>{t===te&&ne()})}te.push(e)}function re(){for(;te.length>0;)ne()}function ie(e){console.warn("https://svelte.dev/e/hydration_mismatch")}let oe,le=!1;function se(e){le=e}function ce(e){if(null===e)throw ie(),G;return oe=e}function de(){return ce($e(oe))}function ue(e){if(le){if(null!==$e(oe))throw ie(),G;oe=e}}function fe(e=1){if(le){for(var t=e,n=oe;t--;)n=$e(n);oe=n}}function he(e=!0){for(var t=0,n=oe;;){if(8===n.nodeType){var a=n.data;if("]"===a){if(0===t)return n;t-=1}else("["===a||"[!"===a||"["===a[0]&&!isNaN(Number(a.slice(1))))&&(t+=1)}var r=$e(n);e&&n.remove(),n=r}}function ge(e){if(!e||8!==e.nodeType)throw ie(),G;return e.data}function ve(e){if("object"!=typeof e||null===e||z in e||I in e)return e;const n=u(e);if(n!==c&&n!==d)return e;var a=new Map,r=t(e),i=jt(0),o=Jt,s=e=>{if(Jt===o)return e();var t=Ft,n=Jt;Nt(null),Xt(o);var a=e();return Nt(t),Xt(n),a};return r&&a.set("length",jt(e.length)),new Proxy(e,{defineProperty(e,t,n){"value"in n&&!1!==n.configurable&&!1!==n.enumerable&&!1!==n.writable||function(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}();var r=a.get(t);return void 0===r?s(()=>{var e=jt(n.value);return a.set(t,e),e}):Pt(r,n.value,!0),!0},deleteProperty(e,t){var n=a.get(t);if(void 0===n){if(t in e){const e=s(()=>jt(W));a.set(t,e),It(i)}}else Pt(n,W),It(i);return!0},get(t,n,r){if(n===z)return e;var i=a.get(n),o=n in t;if(void 0!==i||o&&!l(t,n)?.writable||(i=s(()=>jt(ve(o?t[n]:W))),a.set(n,i)),void 0!==i){var c=cn(i);return c===W?void 0:c}return Reflect.get(t,n,r)},getOwnPropertyDescriptor(e,t){var n=Reflect.getOwnPropertyDescriptor(e,t);if(n&&"value"in n){var r=a.get(t);r&&(n.value=cn(r))}else if(void 0===n){var i=a.get(t),o=i?.v;if(void 0!==i&&o!==W)return{enumerable:!0,configurable:!0,value:o,writable:!0}}return n},has(e,t){if(t===z)return!0;var n=a.get(t),r=void 0!==n&&n.v!==W||Reflect.has(e,t);if((void 0!==n||null!==qt&&(!r||l(e,t)?.writable))&&(void 0===n&&(n=s(()=>jt(r?ve(e[t]):W)),a.set(t,n)),cn(n)===W))return!1;return r},set(e,t,n,o){var c=a.get(t),d=t in e;if(r&&"length"===t)for(var u=n;u<c.v;u+=1){var f=a.get(u+"");void 0!==f?Pt(f,W):u in e&&(f=s(()=>jt(W)),a.set(u+"",f))}void 0===c?d&&!l(e,t)?.writable||(Pt(c=s(()=>jt(void 0)),ve(n)),a.set(t,c)):(d=c.v!==W,Pt(c,s(()=>ve(n))));var h=Reflect.getOwnPropertyDescriptor(e,t);if(h?.set&&h.set.call(o,n),!d){if(r&&"string"==typeof t){var g=a.get("length"),v=Number(t);Number.isInteger(v)&&v>=g.v&&Pt(g,v+1)}It(i)}return!0},ownKeys(e){cn(i);var t=Reflect.ownKeys(e).filter(e=>{var t=a.get(e);return void 0===t||t.v!==W});for(var[n,r]of a)r.v===W||n in e||t.push(n);return t},setPrototypeOf(){!function(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}()}})}function pe(e){try{if(null!==e&&"object"==typeof e&&z in e)return e[z]}catch{}return e}function be(e,t){return Object.is(pe(e),pe(t))}var me,ye,ke,we,Ae;function xe(){if(void 0===me){me=window,ye=document,ke=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,n=Text.prototype;we=l(t,"firstChild").get,Ae=l(t,"nextSibling").get,f(e)&&(e[O]=void 0,e[H]=null,e[F]=void 0,e.__e=void 0),f(n)&&(n[M]=void 0)}}function Ce(e=""){return document.createTextNode(e)}function _e(e){return we.call(e)}function $e(e){return Ae.call(e)}function Le(e,t){if(!le)return _e(e);var n=_e(oe);if(null===n)n=oe.appendChild(Ce());else if(t&&3!==n.nodeType){var a=Ce();return n?.before(a),ce(a),a}return t&&Pe(n),ce(n),n}function Se(eLine truncated
|
||||
+8
-5
@@ -2,18 +2,19 @@
|
||||
/**
|
||||
* Plugin Name: HG Contactformulier
|
||||
* Description: Configureerbaar contactformulier met workflows en talen vanuit de website, zonder inzendingen op te slaan.
|
||||
* Version: 1.2.0
|
||||
* Version: 1.3.0
|
||||
* Requires at least: 6.5
|
||||
* Requires PHP: 8.0
|
||||
* Requires PHP: 8.1
|
||||
* Text Domain: hg-contactform
|
||||
*/
|
||||
if (!defined('ABSPATH')) { exit; }
|
||||
define('HGCF_VERSION','1.2.0');
|
||||
define('HGCF_VERSION','1.3.0');
|
||||
define('HGCF_FILE',__FILE__);
|
||||
require_once __DIR__.'/includes/settings.php';
|
||||
require_once __DIR__.'/includes/language.php';
|
||||
require_once __DIR__.'/includes/form.php';
|
||||
add_action('template_redirect', function () {
|
||||
require_once __DIR__.'/includes/antispam.php';
|
||||
function hgcf_handle_submission() {
|
||||
if(($_SERVER['REQUEST_METHOD']??'')!=='POST' || ($_POST['mlhc_action']??'')!=='send') return;
|
||||
$id=get_queried_object_id(); $post=get_post($id);
|
||||
if(!is_singular() || !$post || (!has_shortcode($post->post_content,'hg_contactform') && !has_shortcode($post->post_content,'mlh_contact'))) wp_die('Invalid form page', '', ['response'=>403]);
|
||||
@@ -30,11 +31,13 @@ add_action('template_redirect', function () {
|
||||
$rate_key='mlhc_rate_'.hash_hmac('sha256',$ip,wp_salt('auth'));
|
||||
$rate=get_transient($rate_key);
|
||||
if($rate && ($rate['count']>=5 || time()-$rate['last']<30)) { $GLOBALS['mlhc_errors']=new WP_Error('rate',hgcf_text('Even geduld: probeer het over een minuut opnieuw of gebruik een andere contactmogelijkheid.','Please wait a minute before trying again, or use another contact option.',$lang)); return; }
|
||||
if(hgcf_altcha_enabled()&&!hgcf_verify_altcha(wp_unslash($_POST['mlhc_altcha']??''),$id)) { $GLOBALS['mlhc_errors']=new WP_Error('altcha',hgcf_text('De antispamcontrole is niet gelukt of verlopen. Probeer de controle opnieuw.','The spam protection check failed or expired. Please verify again.',$lang)); return; }
|
||||
$rate=$rate?:['count'=>0,'last'=>0]; $rate['count']++;$rate['last']=time();set_transient($rate_key,$rate,15*MINUTE_IN_SECONDS);
|
||||
if(!hgcf_send($data,$lang)) { $GLOBALS['mlhc_errors']=new WP_Error('mail',$error); return; }
|
||||
$url=add_query_arg(['contact_status'=>'received','receipt'=>wp_create_nonce('mlhc_received_'.$id)],get_permalink($id));
|
||||
wp_safe_redirect($url.'#contact-form',303);exit;
|
||||
});
|
||||
}
|
||||
add_action('template_redirect','hgcf_handle_submission');
|
||||
add_shortcode('hg_contactform','hgcf_render');
|
||||
add_shortcode('mlh_contact','hgcf_render');
|
||||
add_action('wp_enqueue_scripts',function(){
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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
@@ -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();
|
||||
}
|
||||
@@ -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.');
|
||||
|
||||
Vendored
+21
@@ -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.
|
||||
Vendored
+37
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
) {
|
||||
}
|
||||
}
|
||||
Vendored
+61
@@ -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"
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -1,15 +1,17 @@
|
||||
=== HG Contactformulier ===
|
||||
Requires at least: 6.5
|
||||
Requires PHP: 8.0
|
||||
Stable tag: 1.2.0
|
||||
Requires PHP: 8.1
|
||||
Stable tag: 1.3.0
|
||||
License: GPLv2 or later
|
||||
|
||||
Configureerbaar NL/EN-contactformulier met vraagmodus en optionele afspraakaanvragen.
|
||||
Contactformulier met workflows, talen en optionele lokaal gehoste ALTCHA-antispamcontrole.
|
||||
|
||||
== Installation ==
|
||||
Upload en activeer de plugin. Stel Contactformulier in de beheerzijbalk in en plaats [hg_contactform] op een pagina.
|
||||
|
||||
== Changelog ==
|
||||
= 1.3.0 =
|
||||
Optionele lokale ALTCHA-controle zonder externe diensten, met verlopen en eenmalige uitdagingen. PHP 8.1 of hoger vereist.
|
||||
= 1.2.0 =
|
||||
Nieuw beheer met tabs, meerdere configureerbare workflows, invoerrijen voor diensten en talen vanuit Polylang of de WordPress-sitetaal. Bestaande instellingen worden behouden.
|
||||
= 1.1.0 =
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Vendor pinned official ALTCHA releases; --check only reports available versions."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tarfile
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MANIFEST = ROOT / 'includes/vendor/altcha/versions.json'
|
||||
|
||||
def fetch(url):
|
||||
with urlopen(Request(url, headers={'User-Agent': 'HG-Contactform-dependency-update'}), timeout=30) as response:
|
||||
return response.read()
|
||||
|
||||
def members(blob):
|
||||
with tarfile.open(fileobj=io.BytesIO(blob), mode='r:gz') as archive:
|
||||
return {member.name: archive.extractfile(member).read() for member in archive if member.isfile()}
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--check', action='store_true')
|
||||
parser.add_argument('--widget-version')
|
||||
parser.add_argument('--php-version')
|
||||
args = parser.parse_args()
|
||||
if args.check:
|
||||
current = json.loads(MANIFEST.read_text())
|
||||
widget = json.loads(fetch('https://registry.npmjs.org/altcha/latest'))['version']
|
||||
php = json.loads(fetch('https://api.github.com/repos/altcha-org/altcha-lib-php/releases/latest'))['tag_name'].removeprefix('v')
|
||||
print(f"Widget: installed {current['widget']['version']}, latest {widget}")
|
||||
print(f"PHP: installed {current['php']['version']}, latest {php}")
|
||||
return
|
||||
if not args.widget_version or not args.php_version:
|
||||
parser.error('Supply both explicit versions; no automatic upgrades.')
|
||||
import re
|
||||
if any(not re.fullmatch(r'\d+\.\d+\.\d+', value) for value in (args.widget_version, args.php_version)):
|
||||
parser.error('Use stable x.y.z versions.')
|
||||
metadata = json.loads(fetch(f'https://registry.npmjs.org/altcha/{args.widget_version}'))
|
||||
widget_url = metadata['dist']['tarball']
|
||||
widget_blob = fetch(widget_url)
|
||||
integrity = 'sha512-' + base64.b64encode(hashlib.sha512(widget_blob).digest()).decode()
|
||||
if integrity != metadata['dist']['integrity']:
|
||||
raise RuntimeError('NPM integrity mismatch')
|
||||
php_url = f'https://api.github.com/repos/altcha-org/altcha-lib-php/tarball/v{args.php_version}'
|
||||
php_blob = fetch(php_url)
|
||||
widget_files, php_files = members(widget_blob), members(php_blob)
|
||||
outputs = {
|
||||
'assets/vendor/altcha/widget.js': widget_files['package/dist/main/altcha.i18n.min.js'],
|
||||
'assets/vendor/altcha/LICENSE.txt': widget_files['package/LICENSE.txt'],
|
||||
}
|
||||
for name, data in php_files.items():
|
||||
relative = name.split('/', 1)[1]
|
||||
if relative.startswith('src/') and relative.endswith('.php'):
|
||||
# Private namespace avoids conflicts with other WordPress plugins.
|
||||
outputs['includes/vendor/altcha/' + relative] = data.replace(b'AltchaOrg\\Altcha', b'HGCFVendor\\AltchaOrg\\Altcha')
|
||||
elif relative in ('LICENSE.txt', 'composer.json'):
|
||||
outputs['includes/vendor/altcha/' + relative] = data
|
||||
if 'includes/vendor/altcha/src/Altcha.php' not in outputs:
|
||||
raise RuntimeError('Missing PHP library entry point')
|
||||
# Parse and validate both archives completely before replacing vendored files.
|
||||
php_source = ROOT / 'includes/vendor/altcha/src'
|
||||
if php_source.exists():
|
||||
for old in php_source.rglob('*.php'):
|
||||
if str(old.relative_to(ROOT)) not in outputs:
|
||||
old.unlink()
|
||||
for relative, data in outputs.items():
|
||||
path = ROOT / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
manifest = {
|
||||
'widget': {'version': args.widget_version, 'source': widget_url, 'integrity': integrity},
|
||||
'php': {'version': args.php_version, 'source': php_url, 'archive_sha256': hashlib.sha256(php_blob).hexdigest(), 'namespace': 'HGCFVendor\\AltchaOrg\\Altcha'},
|
||||
'files_sha256': {name: hashlib.sha256(data).hexdigest() for name, data in sorted(outputs.items())},
|
||||
}
|
||||
MANIFEST.write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
print('ALTCHA bundled. Review diff, run security/browser tests, then build the plugin ZIP.')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
if(!defined('WP_CLI')||!WP_CLI)exit;
|
||||
function hgcf_pow_assert($ok,$label){if(!$ok)WP_CLI::error($label);WP_CLI::log('PASS '.$label);}
|
||||
function hgcf_pow_solve($challenge){
|
||||
$c=HGCFVendor\AltchaOrg\Altcha\Challenge::fromArray($challenge);
|
||||
$solution=hgcf_altcha_engine()->solveChallenge(new HGCFVendor\AltchaOrg\Altcha\SolveChallengeOptions(
|
||||
challenge:$c,algorithm:new HGCFVendor\AltchaOrg\Altcha\Algorithm\Pbkdf2(),timeout:20
|
||||
));
|
||||
hgcf_pow_assert($solution!==null,'official PHP solver solves generated challenge');
|
||||
return (new HGCFVendor\AltchaOrg\Altcha\Payload($c,$solution))->toBase64();
|
||||
}
|
||||
$original=hgcf_settings();$config=$original;$override=function()use(&$config){return $config;};add_filter('pre_option_hgcf_settings',$override);
|
||||
$config['altcha_enabled']=true;
|
||||
$challenge=hgcf_create_altcha_challenge(42);$valid=hgcf_pow_solve($challenge);
|
||||
foreach(['',[],str_repeat('A',8193),'invalid',base64_encode('{}'),base64_encode('{"challenge":[]}')] as $raw)hgcf_pow_assert(!hgcf_verify_altcha($raw,42),'malformed or missing proof rejected');
|
||||
hgcf_pow_assert(!hgcf_verify_altcha($valid,43),'proof bound to its form page');
|
||||
foreach(['signature','cost','derivedKey','expiresAt','page','keySignature','counter'] as $field){
|
||||
$tampered=json_decode(base64_decode($valid),true);
|
||||
if($field==='signature')$tampered['challenge']['signature']=str_repeat('0',64);
|
||||
elseif($field==='derivedKey')$tampered['solution']['derivedKey']=str_repeat('0',64);
|
||||
elseif($field==='counter')$tampered['solution']['counter']=1000001;
|
||||
elseif($field==='page')$tampered['challenge']['parameters']['data']['page']=43;
|
||||
else $tampered['challenge']['parameters'][$field]=match($field){'cost'=>1000000000,'expiresAt'=>time()-1,default=>str_repeat('0',64)};
|
||||
hgcf_pow_assert(!hgcf_verify_altcha(base64_encode(wp_json_encode($tampered)),42),'tampered '.$field.' rejected');
|
||||
}
|
||||
hgcf_pow_assert(hgcf_verify_altcha($valid,42),'valid proof accepted');
|
||||
hgcf_pow_assert(!hgcf_verify_altcha($valid,42),'replayed proof rejected');
|
||||
$used='hgcf_pow_used_'.hash('sha256',$challenge['signature']);delete_option($used);
|
||||
$expired=hgcf_altcha_engine()->createChallenge(new HGCFVendor\AltchaOrg\Altcha\CreateChallengeOptions(
|
||||
algorithm:new HGCFVendor\AltchaOrg\Altcha\Algorithm\Pbkdf2(),cost:1000,keyPrefix:'00',expiresAt:time()-1,data:['page'=>42]
|
||||
));
|
||||
hgcf_pow_assert(!hgcf_verify_altcha(hgcf_pow_solve($expired->toArray()),42),'authentic expired proof rejected');
|
||||
$cleanup='hgcf_pow_used_'.hash('sha256','hgcf-test-expired');add_option($cleanup,time()-1,'',false);hgcf_altcha_cleanup();hgcf_pow_assert(get_option($cleanup)===false,'expired replay record cleaned');
|
||||
|
||||
$pages=get_posts(['post_type'=>['page','post'],'post_status'=>'publish','numberposts'=>-1]);$page=null;
|
||||
foreach($pages as $post)if(has_shortcode($post->post_content,'hg_contactform')||has_shortcode($post->post_content,'mlh_contact')){$page=$post;break;}
|
||||
hgcf_pow_assert($page!==null,'existing public form page found');
|
||||
query_posts(['page_id'=>$page->ID]);
|
||||
$savedPost=$_POST;$savedServer=$_SERVER;$_SERVER['REMOTE_ADDR']='192.0.2.123';$_SERVER['REQUEST_METHOD']='POST';
|
||||
$ipKey='hgcf_pow_rate_'.hash_hmac('sha256',$_SERVER['REMOTE_ADDR'],wp_salt('auth'));delete_transient($ipKey);
|
||||
$request=new WP_REST_Request('GET','/hg-contactform/v1/challenge');$request->set_param('page',$page->ID);
|
||||
$response=hgcf_altcha_endpoint($request);hgcf_pow_assert($response instanceof WP_REST_Response&&$response->get_status()===200&&str_contains($response->get_headers()['Cache-Control'],'no-store'),'public challenge endpoint and no-cache');
|
||||
$endpointChallenge=$response->get_data();$proof=hgcf_pow_solve($endpointChallenge);
|
||||
$request->set_param('page',999999999);hgcf_pow_assert(is_wp_error(hgcf_altcha_endpoint($request)),'non-form page rejected');$request->set_param('page',$page->ID);
|
||||
set_transient($ipKey,['count'=>30,'until'=>time()+300],300);hgcf_pow_assert(hgcf_altcha_endpoint($request)->get_error_data()['status']===429,'challenge rate limit');delete_transient($ipKey);
|
||||
$config['altcha_enabled']=false;hgcf_pow_assert(hgcf_altcha_endpoint($request)->get_error_data()['status']===404,'disabled challenge endpoint');ob_start();$off=hgcf_render();ob_end_clean();hgcf_pow_assert(!str_contains($off,'altcha-widget'),'disabled feature has no widget');
|
||||
$config['altcha_enabled']=true;ob_start();$on=hgcf_render(['lang'=>'nl']);ob_end_clean();hgcf_pow_assert(str_contains($on,'altcha-widget')&&str_contains($on,'language="nl"'),'enabled localized widget');
|
||||
$config['workflows']=['question'=>hgcf_workflow_defaults()];$config['recipient']='recipient@example.com';
|
||||
$start=(string)(time()-3);$_POST=['mlhc_action'=>'send','mlhc_nonce'=>wp_create_nonce('hgcf_send'),'mlhc_started'=>$start,'mlhc_signature'=>hash_hmac('sha256',$start,wp_salt('nonce')),'mlhc_name'=>'Test Visitor','mlhc_email'=>'visitor@example.com','mlhc_mode'=>'question','mlhc_message'=>'Integration test without email delivery','mlhc_consent'=>'1'];
|
||||
$sent=[];$mock=function($result,$atts)use(&$sent){$sent[]=$atts;return true;};add_filter('pre_wp_mail',$mock,PHP_INT_MAX,2);
|
||||
$rateKey='mlhc_rate_'.hash_hmac('sha256',$_SERVER['REMOTE_ADDR'],wp_salt('auth'));delete_transient($rateKey);
|
||||
unset($GLOBALS['mlhc_errors']);hgcf_handle_submission();hgcf_pow_assert(count($sent)===0&&($GLOBALS['mlhc_errors']->get_error_code()??'')==='altcha','real handler rejects missing proof before mail');
|
||||
$_POST['mlhc_altcha']='invalid';unset($GLOBALS['mlhc_errors']);hgcf_handle_submission();hgcf_pow_assert(count($sent)===0&&$GLOBALS['mlhc_errors']->get_error_code()==='altcha','real handler rejects forged proof');
|
||||
$_POST['mlhc_altcha']=$proof;unset($GLOBALS['mlhc_errors']);
|
||||
$redirect=function($location){throw new RuntimeException('hgcf-test-redirect');};add_filter('wp_redirect',$redirect);
|
||||
try{hgcf_handle_submission();}catch(RuntimeException $e){hgcf_pow_assert($e->getMessage()==='hgcf-test-redirect','successful handler redirects');}
|
||||
remove_filter('wp_redirect',$redirect);
|
||||
hgcf_pow_assert(count($sent)===1&&!isset($GLOBALS['mlhc_errors']),'valid proof reaches mock mail');
|
||||
delete_transient($rateKey);hgcf_handle_submission();hgcf_pow_assert(count($sent)===1&&$GLOBALS['mlhc_errors']->get_error_code()==='altcha','handler rejects replay before mail');
|
||||
delete_option('hgcf_pow_used_'.hash('sha256',$endpointChallenge['signature']));delete_transient($rateKey);delete_transient($ipKey);
|
||||
remove_filter('pre_wp_mail',$mock,PHP_INT_MAX);$_POST=$savedPost;$_SERVER=$savedServer;unset($GLOBALS['mlhc_errors']);wp_reset_query();
|
||||
$config=$original;$out=hgcf_sanitize_settings(['altcha_enabled'=>'1']);hgcf_pow_assert($out['altcha_enabled']===true,'enable via settings');$out=hgcf_sanitize_settings(['altcha_enabled'=>'0']);hgcf_pow_assert($out['altcha_enabled']===false,'disable via settings');
|
||||
$out=hgcf_sanitize_settings(['altcha_enabled'=>['bad']]);hgcf_pow_assert($out['altcha_enabled']===$original['altcha_enabled'],'malformed setting preserves value');
|
||||
remove_filter('pre_option_hgcf_settings',$override);
|
||||
WP_CLI::success('ALTCHA verification, replay protection, endpoint and real handler passed; no email sent.');
|
||||
@@ -0,0 +1,82 @@
|
||||
// Usage: HGCF_BASE_URL=https://test.example PLAYWRIGHT_MODULE=/path/to/playwright node tests/browser.cjs /contact/ /en/contact/
|
||||
// Valid form POSTs are intercepted in the browser; they never reach the mail handler.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const base = process.env.HGCF_BASE_URL;
|
||||
if (!base || process.argv.length < 3) throw new Error('Provide HGCF_BASE_URL and contact page paths.');
|
||||
const artifacts = process.env.HGCF_ARTIFACTS || '/tmp/hg-contact-browser';
|
||||
fs.mkdirSync(artifacts, { recursive: true, mode: 0o700 });
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const proofs = [];
|
||||
try {
|
||||
for (const [index, route] of process.argv.slice(2).entries()) {
|
||||
for (const mobile of [false, true]) {
|
||||
const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 } });
|
||||
const page = await context.newPage();
|
||||
const errors = []; const requests = []; let submitted = null;
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
page.on('request', request => requests.push(request.url()));
|
||||
const url = new URL(route, base).href;
|
||||
await page.route('**/*', async handler => {
|
||||
const request = handler.request();
|
||||
if (request.method() === 'POST' && new URL(request.url()).pathname === new URL(url).pathname) {
|
||||
submitted = Object.fromEntries(new URLSearchParams(request.postData()));
|
||||
await handler.fulfill({ status: 200, contentType: 'text/html', body: '<p>Test POST intercepted; no mail sent.</p>' });
|
||||
} else await handler.continue();
|
||||
});
|
||||
const response = await page.goto(url, { waitUntil: 'networkidle' });
|
||||
assert.equal(response.status(), 200);
|
||||
await page.waitForFunction(() => !!customElements.get('altcha-widget'));
|
||||
const widget = page.locator('altcha-widget');
|
||||
assert.equal(await widget.count(), 1);
|
||||
const lang = await widget.getAttribute('language');
|
||||
assert.equal(await page.locator('script#hgcf-altcha-js').getAttribute('type'), 'module');
|
||||
const challengeURL = await widget.getAttribute('challenge');
|
||||
assert.equal(new URL(challengeURL).origin, new URL(base).origin);
|
||||
assert(await page.locator('.mlhc-form').evaluate(form => !form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))));
|
||||
assert.equal(await page.locator('.mlhc-form button[type=submit]').isDisabled(), false);
|
||||
await page.locator('[name=mlhc_name]').fill('Test Visitor');
|
||||
await page.locator('[name=mlhc_email]').fill('visitor@example.com');
|
||||
await page.locator('[name=mlhc_message]').fill('Browser verification test intercepted before delivery.');
|
||||
await page.locator('[name=mlhc_consent]').check();
|
||||
await page.waitForFunction(() => {
|
||||
const input = document.querySelector('.mlhc-form input[name=mlhc_altcha]');
|
||||
return !!input?.value;
|
||||
}, null, { timeout: 45000 }).catch(async error => {
|
||||
console.error('Widget diagnostic', await widget.textContent(), errors);
|
||||
await page.screenshot({ path: path.join(artifacts, 'failure.png'), fullPage: true });
|
||||
throw error;
|
||||
});
|
||||
const proof = await page.locator('input[name=mlhc_altcha]').inputValue();
|
||||
const decoded = JSON.parse(Buffer.from(proof, 'base64').toString());
|
||||
assert.equal(decoded.challenge.parameters.algorithm, 'PBKDF2/SHA-256');
|
||||
assert.equal(decoded.challenge.parameters.data.page, Number(new URL(challengeURL).searchParams.get('page')));
|
||||
assert(await widget.textContent().then(text => text.includes(lang === 'nl' ? 'Geverifieerd' : 'Verified')));
|
||||
assert.equal(await page.locator('[data-hgcf-field=service]').isVisible(), false);
|
||||
const requestMode = page.locator('[name=mlhc_mode][value=request]');
|
||||
if (await requestMode.count()) {
|
||||
await requestMode.check();
|
||||
assert.equal(await page.locator('[data-hgcf-field=service]').isVisible(), true);
|
||||
assert.equal(await page.locator('[name=mlhc_message]').getAttribute('required'), null);
|
||||
await page.locator('[name=mlhc_mode][value=question]').check();
|
||||
}
|
||||
const geometry = await widget.boundingBox();
|
||||
assert(geometry.x >= 0 && geometry.x + geometry.width <= (mobile ? 390 : 1440));
|
||||
await page.locator('.hgcf-contact').screenshot({ path: path.join(artifacts, `form-${lang}-${mobile ? 'mobile' : 'desktop'}.png`) });
|
||||
assert.deepEqual(errors, []);
|
||||
const runtimeExternal = requests.filter(request => new URL(request).protocol.startsWith('http') && new URL(request).origin !== new URL(base).origin);
|
||||
assert.deepEqual(runtimeExternal, [], 'No external requests from contact page or ALTCHA');
|
||||
await page.locator('.mlhc-form button[type=submit]').click();
|
||||
await page.waitForFunction(() => document.body.textContent.includes('Test POST intercepted'));
|
||||
assert.equal(submitted.mlhc_altcha, proof);
|
||||
proofs.push({ page: decoded.challenge.parameters.data.page, proof });
|
||||
console.log(`PASS ${lang} ${mobile ? 'mobile' : 'desktop'}: local widget, solved proof, workflow switch, submit interception, no console errors`);
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(path.join(artifacts, 'proofs.json'), JSON.stringify(proofs), { mode: 0o600 });
|
||||
} finally { await browser.close(); }
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
Reference in new issue
Block a user