Add optional self-hosted ALTCHA protection and dependency maintenance
This commit is contained in:
1 parent
3b558409f3
commit
2a2f1d5878
59 files changed
+2648
-12
No files matched your search
@@ -0,0 +1,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