v1.5.1: frontend auth hardening — rate limiting, email verification, honeypots, CSV safety

Security-only release per ADR-0001. Closes all six ship-blockers from the
post-v1.5.0 audit: PSEC-001 (no rate limiting), PSEC-002 (account
enumeration via separate error messages), PSEC-003 (registration auto-login
with no email verification), PSEC-004 (ungated "My Data" templates),
PSEC-005 (CSV formula injection on subscriber export), PSEC-006 (no
honeypot/CAPTCHA on public forms).

Adds inc/config.php (single source of truth for all security thresholds,
filterable via peptide_starter_security_config), inc/rate-limiter.php
(Peptide_Starter_Rate_Limiter + Cloudflare-aware client IP resolver,
transient-backed, never stores raw IPs), and inc/email-verification.php
(43-char token, 24h TTL, /verify rewrite, rate-limited resend endpoint).

Auth handlers rewritten to: unify all failure messages, rate-limit before
any expensive check, drop registrations with a filled honeypot silently,
stop auto-login on register, send a verification email instead. The
require_login() helper lives in inc/helpers.php and is applied at the top
of page-tracker.php, page-subject-log.php, and page-protocol-builder.php;
page-calculator.php stays open (no PII, no writes).

Newsletter signup gains: consent checkbox, privacy link, honeypot,
autoload=false on the wp_options blob, unsubscribe token stored per row,
/newsletter-unsubscribe route, merged success+duplicate into a single "ok"
state. Admin export runs every cell through peptide_starter_csv_safe()
which prefixes leading =/+/-/@/tab/CR with a quote.

Contact handler hardens against email-header injection (rejects name
values with \r \n , < >), rate-limits, honors honeypot, tags mail
failures with a request ID for correlation without logging message
content.

Adds Tools → Mail Test (inc/mail-diagnostic.php): a permanent wp_mail
probe so we can check Hostinger outbound deliverability any time it looks
flaky. Adds a one-time admin_init migration that enrols pre-v1.5.1
subscribers into the verification flow (currently a no-op — zero users —
but guarded for the future).

Other cleanup from the audit: fallback primary menu moved out of
header.php into inc/helpers.php (redeclaration risk), placeholder footer
language links replaced with "Translations coming soon", footer copyright
now reads through the customizer getter, settings-panel gains a proper
Tab/Shift+Tab focus trap and saves/restores body overflow, documentation
heading IDs slugified from heading text with collision counters, JS files
standardized on const/let.

Six new PHPUnit suites cover rate limiter lifecycle, auth handler error
unification and rate limits, email verification token generation and
expiry, contact handler header injection + rate limit + honeypot,
newsletter signup consent + CSV safety, and require_login gate behavior.

ARCHITECTURE.md and CONVENTIONS.md updated in the same commit — new
module layout, data flows, security patterns for rate-limiting,
honeypotting, gating, and CSV-safe export.

Version bumped to 1.5.1 in style.css and functions.php.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
peptiderepo
2026-04-14 13:01:22 +07:00
parent d28d5f45d5
commit cb8b73f4ab
34 changed files with 2816 additions and 745 deletions

64
tests/test-auth-gate.php Normal file
View File

@@ -0,0 +1,64 @@
<?php
/**
* Tests for peptide_starter_require_login() helper.
*
* @package peptide-starter
*/
class Test_Auth_Gate extends WP_UnitTestCase {
/**
* @var string|null Captured redirect target.
*/
protected $redirect = null;
public function set_up() {
parent::set_up();
$this->redirect = null;
add_filter(
'wp_redirect',
function ( $url ) {
$this->redirect = $url;
return false;
}
);
}
public function tear_down() {
remove_all_filters( 'wp_redirect' );
wp_set_current_user( 0 );
parent::tear_down();
}
public function test_anonymous_user_redirected_to_auth() {
$_SERVER['REQUEST_URI'] = '/tracker';
try { peptide_starter_require_login(); } catch ( Exception $e ) { /* exit */ }
$this->assertNotNull( $this->redirect );
$this->assertStringContainsString( '/auth', (string) $this->redirect );
$this->assertStringContainsString( 'redirect_to=', (string) $this->redirect );
}
public function test_unverified_user_redirected_to_profile_banner() {
$user_id = self::factory()->user->create();
update_user_meta( $user_id, 'ps_pending_verification', 1 );
wp_set_current_user( $user_id );
try { peptide_starter_require_login(); } catch ( Exception $e ) { /* exit */ }
$this->assertNotNull( $this->redirect );
$this->assertStringContainsString( 'verify_required=1', (string) $this->redirect );
}
public function test_verified_logged_in_user_passes_through() {
$user_id = self::factory()->user->create();
wp_set_current_user( $user_id );
$reached = false;
try {
peptide_starter_require_login();
$reached = true;
} catch ( Exception $e ) { /* would be redirect */ }
$this->assertTrue( $reached );
$this->assertNull( $this->redirect );
}
}

View File

@@ -0,0 +1,152 @@
<?php
/**
* Tests for inc/auth-handlers.php.
*
* Covers: unified error messages, rate limiting, nonce failure,
* honeypot drop, enumeration resistance.
*
* @package peptide-starter
*/
/**
* @runTestsInSeparateProcesses disabled — WP_UnitTestCase handles isolation.
*/
class Test_Auth_Handlers extends WP_UnitTestCase {
/**
* Capture wp_send_json_{success,error} via wp_die_handler so tests can
* assert on the response without ending the PHP process.
*
* @var array|null
*/
protected $captured = null;
public function set_up() {
parent::set_up();
$this->captured = null;
// Swap wp_die into a throwable we can catch.
add_filter( 'wp_die_ajax_handler', array( $this, 'get_die_handler' ) );
add_filter( 'wp_die_handler', array( $this, 'get_die_handler' ) );
// Capture the JSON body via the wp_json_encode filter path.
add_filter(
'wp_json_encode_data',
function ( $data ) {
$this->captured = $data;
return $data;
}
);
}
public function tear_down() {
remove_all_filters( 'wp_die_ajax_handler' );
remove_all_filters( 'wp_die_handler' );
remove_all_filters( 'wp_json_encode_data' );
global $wpdb;
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_ps_rl_%'" );
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_ps_rl_%'" );
$_POST = array();
parent::tear_down();
}
public function get_die_handler() {
return array( $this, 'throwing_die' );
}
public function throwing_die( $message = '', $title = '', $args = array() ) {
throw new WPAjaxDieStopException( is_scalar( $message ) ? (string) $message : wp_json_encode( $message ) );
}
/**
* Run the login handler and return the captured response, if any.
*/
protected function invoke_login() {
try {
peptide_starter_ajax_login();
} catch ( WPAjaxDieStopException $e ) {
// Expected — JSON was sent.
return;
}
}
public function test_login_missing_nonce_rejects_with_security_message() {
$_POST = array( 'email' => 'a@b.com', 'password' => 'whatever' );
$this->invoke_login();
$this->assertIsArray( $this->captured );
$this->assertFalse( $this->captured['success'] );
$this->assertStringContainsString( 'Security check', $this->captured['data']['message'] );
}
public function test_login_unknown_email_returns_unified_message() {
$_POST = array(
'ps_login_nonce' => wp_create_nonce( 'ps_auth_login' ),
'email' => 'nobody-' . wp_generate_password( 8, false ) . '@example.com',
'password' => 'wrong-password',
);
$this->invoke_login();
$this->assertSame( peptide_starter_login_failure_message(), $this->captured['data']['message'] );
}
public function test_login_wrong_password_returns_unified_message() {
$user = self::factory()->user->create_and_get( array( 'user_pass' => 'correct-horse-battery' ) );
$_POST = array(
'ps_login_nonce' => wp_create_nonce( 'ps_auth_login' ),
'email' => $user->user_email,
'password' => 'definitely-wrong',
);
$this->invoke_login();
$this->assertSame( peptide_starter_login_failure_message(), $this->captured['data']['message'] );
}
public function test_login_honeypot_tripped_returns_fake_success() {
$_POST = array(
'ps_login_nonce' => wp_create_nonce( 'ps_auth_login' ),
'email' => 'a@b.com',
'password' => 'x',
'ps_hp_login' => 'botfill',
);
$this->invoke_login();
$this->assertTrue( $this->captured['success'], 'Honeypot must silently fake success.' );
}
public function test_login_rate_limit_exceeded_still_returns_unified_message() {
// Exhaust the budget.
$config = peptide_starter_config_rate_limit( 'login' );
for ( $i = 0; $i < $config['limit']; $i++ ) {
Peptide_Starter_Rate_Limiter::record( 'login', peptide_starter_hash_identifier( 'same@same.com' ) );
}
$_POST = array(
'ps_login_nonce' => wp_create_nonce( 'ps_auth_login' ),
'email' => 'same@same.com',
'password' => 'anything',
);
$this->invoke_login();
$this->assertSame( peptide_starter_login_failure_message(), $this->captured['data']['message'] );
}
public function test_register_invalid_username_returns_unified_message() {
$_POST = array(
'ps_register_nonce' => wp_create_nonce( 'ps_auth_register' ),
'username' => 'ab',
'email' => 'newuser@example.com',
'password' => 'longenoughpassword',
);
update_option( 'users_can_register', 1 );
try { peptide_starter_ajax_register(); } catch ( WPAjaxDieStopException $e ) { /* ok */ }
$this->assertSame( peptide_starter_register_failure_message(), $this->captured['data']['message'] );
}
public function test_register_duplicate_email_returns_unified_message() {
self::factory()->user->create( array( 'user_email' => 'dup@example.com' ) );
update_option( 'users_can_register', 1 );
$_POST = array(
'ps_register_nonce' => wp_create_nonce( 'ps_auth_register' ),
'username' => 'newusername',
'email' => 'dup@example.com',
'password' => 'longenoughpassword',
);
try { peptide_starter_ajax_register(); } catch ( WPAjaxDieStopException $e ) { /* ok */ }
$this->assertSame( peptide_starter_register_failure_message(), $this->captured['data']['message'] );
}
}

View File

@@ -0,0 +1,110 @@
<?php
/**
* Tests for inc/contact-handler.php.
*
* @package peptide-starter
*/
class Test_Contact_Handler extends WP_UnitTestCase {
protected $captured = null;
public function set_up() {
parent::set_up();
$this->captured = null;
add_filter(
'wp_die_ajax_handler',
function () {
return array( $this, 'throwing_die' );
}
);
add_filter(
'wp_die_handler',
function () {
return array( $this, 'throwing_die' );
}
);
add_filter(
'wp_json_encode_data',
function ( $data ) {
$this->captured = $data;
return $data;
}
);
add_filter(
'pre_wp_mail',
function () {
return true;
}
);
}
public function tear_down() {
remove_all_filters( 'wp_die_ajax_handler' );
remove_all_filters( 'wp_die_handler' );
remove_all_filters( 'wp_json_encode_data' );
remove_all_filters( 'pre_wp_mail' );
global $wpdb;
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_ps_rl_%'" );
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_ps_rl_%'" );
$_POST = array();
parent::tear_down();
}
public function throwing_die( $message = '' ) {
throw new WPAjaxDieStopException( is_scalar( $message ) ? (string) $message : wp_json_encode( $message ) );
}
protected function post( $overrides = array() ) {
$defaults = array(
'ps_contact_nonce' => wp_create_nonce( 'ps_contact_form' ),
'name' => 'Dr Valid',
'email' => 'valid@example.com',
'topic' => 'bug',
'message' => 'There is a bug in the tracker.',
);
$_POST = array_merge( $defaults, $overrides );
try { peptide_starter_ajax_contact(); } catch ( WPAjaxDieStopException $e ) { /* ok */ }
}
public function test_valid_submission_succeeds() {
$this->post();
$this->assertTrue( $this->captured['success'] );
}
public function test_nonce_failure_rejects() {
$this->post( array( 'ps_contact_nonce' => 'bogus' ) );
$this->assertFalse( $this->captured['success'] );
$this->assertStringContainsString( 'Security', $this->captured['data']['message'] );
}
public function test_name_with_newline_rejected_for_header_injection() {
$this->post( array( 'name' => "Mallory\r\nBcc: attacker@x.com" ) );
$this->assertFalse( $this->captured['success'] );
}
public function test_name_with_angle_brackets_rejected() {
$this->post( array( 'name' => 'Alice <injected@x.com>' ) );
$this->assertFalse( $this->captured['success'] );
}
public function test_invalid_topic_rejected() {
$this->post( array( 'topic' => 'not-an-allowlisted-topic' ) );
$this->assertFalse( $this->captured['success'] );
}
public function test_honeypot_returns_fake_success() {
$this->post( array( 'ps_hp_contact' => 'filled-by-bot' ) );
$this->assertTrue( $this->captured['success'] );
}
public function test_rate_limit_exceeded_rejects() {
$config = peptide_starter_config_rate_limit( 'contact' );
for ( $i = 0; $i < $config['limit']; $i++ ) {
Peptide_Starter_Rate_Limiter::record( 'contact', 'ip' );
}
$this->post();
$this->assertFalse( $this->captured['success'] );
$this->assertStringContainsString( 'Too many', $this->captured['data']['message'] );
}
}

View File

@@ -0,0 +1,103 @@
<?php
/**
* Tests for inc/email-verification.php.
*
* @package peptide-starter
*/
class Test_Email_Verification extends WP_UnitTestCase {
public function set_up() {
parent::set_up();
// Capture wp_mail without sending.
add_filter(
'pre_wp_mail',
function () {
return true;
}
);
}
public function tear_down() {
remove_all_filters( 'pre_wp_mail' );
parent::tear_down();
}
public function test_send_sets_meta_and_returns_true() {
$user_id = self::factory()->user->create();
$sent = peptide_starter_send_verification_email( $user_id );
$this->assertTrue( $sent );
$this->assertSame( '1', (string) get_user_meta( $user_id, 'ps_pending_verification', true ) );
$this->assertNotEmpty( get_user_meta( $user_id, 'ps_verify_token', true ) );
$this->assertGreaterThan( time(), (int) get_user_meta( $user_id, 'ps_verify_expires', true ) );
}
public function test_user_is_verified_default_without_meta() {
$user_id = self::factory()->user->create();
$this->assertTrue( peptide_starter_user_is_verified( $user_id ) );
}
public function test_user_is_unverified_with_pending_meta() {
$user_id = self::factory()->user->create();
update_user_meta( $user_id, 'ps_pending_verification', 1 );
$this->assertFalse( peptide_starter_user_is_verified( $user_id ) );
}
public function test_verification_handler_rejects_bad_token() {
$user_id = self::factory()->user->create();
peptide_starter_send_verification_email( $user_id );
$_GET['uid'] = $user_id;
$_GET['token'] = 'obviously-wrong';
set_query_var( 'ps_verify', 1 );
$redirected = null;
add_filter(
'wp_redirect',
function ( $url ) use ( &$redirected ) {
$redirected = $url;
return false;
}
);
try {
peptide_starter_handle_verify_request();
} catch ( Exception $e ) { /* wp_safe_redirect + exit */ }
$this->assertNotNull( $redirected );
$this->assertStringContainsString( 'verify_error=1', (string) $redirected );
remove_all_filters( 'wp_redirect' );
set_query_var( 'ps_verify', 0 );
}
public function test_verification_handler_rejects_expired_token() {
$user_id = self::factory()->user->create();
$token = wp_generate_password( 43, false, false );
update_user_meta( $user_id, 'ps_pending_verification', 1 );
update_user_meta( $user_id, 'ps_verify_token', $token );
update_user_meta( $user_id, 'ps_verify_expires', time() - 10 );
$_GET['uid'] = $user_id;
$_GET['token'] = $token;
set_query_var( 'ps_verify', 1 );
$redirected = null;
add_filter(
'wp_redirect',
function ( $url ) use ( &$redirected ) {
$redirected = $url;
return false;
}
);
try {
peptide_starter_handle_verify_request();
} catch ( Exception $e ) { /* ok */ }
$this->assertNotNull( $redirected );
$this->assertStringContainsString( 'verify_error=1', (string) $redirected );
remove_all_filters( 'wp_redirect' );
set_query_var( 'ps_verify', 0 );
}
}

96
tests/test-newsletter.php Normal file
View File

@@ -0,0 +1,96 @@
<?php
/**
* Tests for newsletter signup handler + CSV-safe export helper.
*
* @package peptide-starter
*/
class Test_Newsletter extends WP_UnitTestCase {
public function tear_down() {
global $wpdb;
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_ps_rl_%'" );
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_ps_rl_%'" );
delete_option( 'ps_newsletter_emails' );
$_POST = array();
parent::tear_down();
}
public function test_csv_safe_prefixes_dangerous_leading_chars() {
$this->assertSame( "'=cmd|' /C calc'!A0", peptide_starter_csv_safe( "=cmd|' /C calc'!A0" ) );
$this->assertSame( "'+1234", peptide_starter_csv_safe( '+1234' ) );
$this->assertSame( "'-1234", peptide_starter_csv_safe( '-1234' ) );
$this->assertSame( "'@evil", peptide_starter_csv_safe( '@evil' ) );
$this->assertSame( "'\tTab", peptide_starter_csv_safe( "\tTab" ) );
$this->assertSame( "'\rCR", peptide_starter_csv_safe( "\rCR" ) );
}
public function test_csv_safe_passes_safe_values_through() {
$this->assertSame( 'alice@example.com', peptide_starter_csv_safe( 'alice@example.com' ) );
$this->assertSame( '2026-04-14 10:30:00', peptide_starter_csv_safe( '2026-04-14 10:30:00' ) );
$this->assertSame( '', peptide_starter_csv_safe( '' ) );
}
public function test_signup_stores_email_with_unsub_token() {
$_POST = array(
'ps_newsletter_nonce' => wp_create_nonce( 'peptide_starter_newsletter' ),
'email' => 'sub@example.com',
'ps_consent' => '1',
);
$this->invoke_signup();
$emails = get_option( 'ps_newsletter_emails', array() );
$this->assertCount( 1, $emails );
$this->assertSame( 'sub@example.com', $emails[0]['email'] );
$this->assertNotEmpty( $emails[0]['unsub_token'] );
}
public function test_signup_without_consent_rejected() {
$_POST = array(
'ps_newsletter_nonce' => wp_create_nonce( 'peptide_starter_newsletter' ),
'email' => 'nope@example.com',
);
$this->invoke_signup();
$emails = get_option( 'ps_newsletter_emails', array() );
$this->assertCount( 0, $emails );
}
public function test_signup_duplicate_does_not_add_second_row() {
$initial = array(
array(
'email' => 'dup@example.com',
'date' => '2026-04-10 00:00:00',
'unsub_token' => 'abc',
),
);
update_option( 'ps_newsletter_emails', $initial, false );
$_POST = array(
'ps_newsletter_nonce' => wp_create_nonce( 'peptide_starter_newsletter' ),
'email' => 'dup@example.com',
'ps_consent' => '1',
);
$this->invoke_signup();
$emails = get_option( 'ps_newsletter_emails', array() );
$this->assertCount( 1, $emails );
}
/**
* Invoke the handler and catch the wp_safe_redirect exit.
*/
protected function invoke_signup() {
$captured = null;
$filter = function ( $url ) use ( &$captured ) {
$captured = $url;
return false;
};
add_filter( 'wp_redirect', $filter );
try {
peptide_starter_handle_newsletter_signup();
} catch ( Exception $e ) { /* exit path */ }
remove_filter( 'wp_redirect', $filter );
}
}

View File

@@ -0,0 +1,94 @@
<?php
/**
* Tests for inc/rate-limiter.php and inc/config.php.
*
* @package peptide-starter
*/
/**
* Rate limiter check / record / reset lifecycle and filterability.
*/
class Test_Rate_Limiter extends WP_UnitTestCase {
/**
* Reset all transients we touched between tests.
*/
public function tear_down() {
global $wpdb;
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_ps_rl_%'" );
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_ps_rl_%'" );
remove_all_filters( 'peptide_starter_security_config' );
parent::tear_down();
}
public function test_check_allows_under_limit() {
$this->assertTrue( Peptide_Starter_Rate_Limiter::check( 'login', 'user-a' ) );
}
public function test_record_increments_and_eventually_blocks() {
$config = peptide_starter_config_rate_limit( 'login' );
for ( $i = 0; $i < $config['limit']; $i++ ) {
Peptide_Starter_Rate_Limiter::record( 'login', 'user-b' );
}
$this->assertFalse(
Peptide_Starter_Rate_Limiter::check( 'login', 'user-b' ),
'check() must return false after recording limit-many attempts.'
);
}
public function test_reset_clears_counter() {
$config = peptide_starter_config_rate_limit( 'login' );
for ( $i = 0; $i < $config['limit']; $i++ ) {
Peptide_Starter_Rate_Limiter::record( 'login', 'user-c' );
}
Peptide_Starter_Rate_Limiter::reset( 'login', 'user-c' );
$this->assertTrue( Peptide_Starter_Rate_Limiter::check( 'login', 'user-c' ) );
}
public function test_identifiers_are_isolated() {
$config = peptide_starter_config_rate_limit( 'login' );
for ( $i = 0; $i < $config['limit']; $i++ ) {
Peptide_Starter_Rate_Limiter::record( 'login', 'user-d' );
}
$this->assertTrue(
Peptide_Starter_Rate_Limiter::check( 'login', 'user-e' ),
'Recording against user-d must not affect user-e.'
);
}
public function test_filter_override_changes_limit() {
add_filter(
'peptide_starter_security_config',
function ( $c ) {
$c['rate_limits']['login']['limit'] = 1;
return $c;
}
);
Peptide_Starter_Rate_Limiter::record( 'login', 'user-f' );
$this->assertFalse( Peptide_Starter_Rate_Limiter::check( 'login', 'user-f' ) );
}
public function test_hash_identifier_is_stable_and_non_reversible() {
$a = peptide_starter_hash_identifier( 'alice@example.com' );
$b = peptide_starter_hash_identifier( 'alice@example.com' );
$c = peptide_starter_hash_identifier( 'bob@example.com' );
$this->assertSame( $a, $b );
$this->assertNotSame( $a, $c );
$this->assertSame( 32, strlen( $a ) );
$this->assertStringNotContainsString( 'alice', $a );
}
public function test_client_ip_prefers_cf_header() {
$_SERVER['HTTP_CF_CONNECTING_IP'] = '203.0.113.5';
$_SERVER['REMOTE_ADDR'] = '10.0.0.1';
$this->assertSame( '203.0.113.5', peptide_starter_get_client_ip() );
unset( $_SERVER['HTTP_CF_CONNECTING_IP'] );
}
public function test_client_ip_rejects_garbage() {
$_SERVER['HTTP_CF_CONNECTING_IP'] = 'not-an-ip';
$_SERVER['REMOTE_ADDR'] = '10.0.0.1';
$this->assertSame( '10.0.0.1', peptide_starter_get_client_ip() );
unset( $_SERVER['HTTP_CF_CONNECTING_IP'] );
}
}