Files
peptide-starter-theme/assets/js/settings-panel.js
peptiderepo cb8b73f4ab 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>
2026-04-14 13:01:22 +07:00

165 lines
5.0 KiB
JavaScript

/**
* Settings Panel — Open/Close, Focus Trap, Contact Form AJAX
* Peptide Starter Theme
*
* Handles:
* - Open / close the slide-out panel (button, overlay click, Escape)
* - Save and restore document.body.style.overflow so other panels
* opening the overlay don't stomp on the caller's original value
* - Focus trap: Tab / Shift+Tab wrap within the panel while it's open
* - AJAX submission of the contact form with XSS-safe status rendering
*
* @see template-parts/settings-panel.php — panel HTML
* @see header.php — trigger button
* @see inc/contact-handler.php — AJAX endpoint
*/
(function () {
'use strict';
const panel = document.getElementById('ps-settings-panel');
const overlay = document.getElementById('ps-settings-overlay');
const closeBtn = document.getElementById('ps-settings-close');
const openBtn = document.getElementById('ps-settings-toggle');
const contactForm = document.getElementById('ps-contact-form');
const statusEl = document.getElementById('ps-contact-status');
if (!panel || !overlay) {
return;
}
const FOCUSABLE = 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
let previousOverflow = '';
let firstFocusable = null;
let lastFocusable = null;
/**
* Snapshot and refresh the focusable boundary elements inside the panel.
* Called on open so dynamically-rendered fields are included.
*/
function refreshFocusables() {
const list = panel.querySelectorAll(FOCUSABLE);
if (!list.length) {
firstFocusable = null;
lastFocusable = null;
return;
}
firstFocusable = list[0];
lastFocusable = list[list.length - 1];
}
function openPanel() {
panel.classList.add('ps-settings-panel--open');
panel.setAttribute('aria-hidden', 'false');
overlay.classList.add('ps-settings-overlay--active');
overlay.setAttribute('aria-hidden', 'false');
previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
refreshFocusables();
if (closeBtn) {
setTimeout(function () { closeBtn.focus(); }, 100);
}
}
function closePanel() {
panel.classList.remove('ps-settings-panel--open');
panel.setAttribute('aria-hidden', 'true');
overlay.classList.remove('ps-settings-overlay--active');
overlay.setAttribute('aria-hidden', 'true');
document.body.style.overflow = previousOverflow;
previousOverflow = '';
if (openBtn) {
openBtn.focus();
}
}
function trapFocus(e) {
if (!panel.classList.contains('ps-settings-panel--open')) return;
if (e.key !== 'Tab') return;
if (!firstFocusable || !lastFocusable) return;
if (e.shiftKey && document.activeElement === firstFocusable) {
e.preventDefault();
lastFocusable.focus();
} else if (!e.shiftKey && document.activeElement === lastFocusable) {
e.preventDefault();
firstFocusable.focus();
}
}
if (openBtn) { openBtn.addEventListener('click', openPanel); }
if (closeBtn) { closeBtn.addEventListener('click', closePanel); }
overlay.addEventListener('click', closePanel);
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && panel.classList.contains('ps-settings-panel--open')) {
closePanel();
}
});
document.addEventListener('keydown', trapFocus);
// Contact form AJAX.
if (contactForm) {
contactForm.addEventListener('submit', function (e) {
e.preventDefault();
if (!contactForm.checkValidity()) {
contactForm.reportValidity();
return;
}
const formData = new FormData(contactForm);
const btn = contactForm.querySelector('button[type="submit"]');
const origText = btn.textContent;
btn.disabled = true;
btn.textContent = '...';
if (statusEl) { statusEl.innerHTML = ''; }
const xhr = new XMLHttpRequest();
const url = (typeof window.peptideStarterData !== 'undefined' && window.peptideStarterData.ajaxUrl)
? window.peptideStarterData.ajaxUrl
: '/wp-admin/admin-ajax.php';
xhr.open('POST', url);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function () {
btn.disabled = false;
btn.textContent = origText;
let resp;
try { resp = JSON.parse(xhr.responseText); } catch (ex) {
renderStatus('An unexpected error occurred.', 'error');
return;
}
if (resp && resp.success) {
renderStatus((resp.data && resp.data.message) || 'Message sent.', 'success');
contactForm.reset();
} else {
renderStatus((resp && resp.data && resp.data.message) || 'Failed to send.', 'error');
}
};
xhr.onerror = function () {
btn.disabled = false;
btn.textContent = origText;
renderStatus('Network error. Please try again.', 'error');
};
xhr.send(formData);
});
}
function renderStatus(text, type) {
if (!statusEl) return;
const wrap = document.createElement('div');
wrap.className = 'ps-alert ps-alert-' + (type || 'info');
const p = document.createElement('p');
p.textContent = text;
wrap.appendChild(p);
statusEl.innerHTML = '';
statusEl.appendChild(wrap);
}
})();