Files
peptide-starter-theme/assets/js/documentation.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

135 lines
3.6 KiB
JavaScript

/**
* Documentation Page — Table of Contents & Scroll Spy
* Peptide Starter Theme
*
* Handles:
* - Auto-generates ToC from h2 headings
* - Slugifies heading IDs from the heading text (with collision counter)
* so deep links survive edits that change the author's order
* - IntersectionObserver scroll spy highlights the active section
* - Smooth scroll with header offset on ToC click
* - Collapses sidebar to dropdown on mobile
*
* @see page-documentation.php — renders the two-column layout
*/
(function () {
'use strict';
const docsBody = document.getElementById('ps-docs-body');
const tocList = document.getElementById('ps-docs-toc-list');
const sidebar = document.querySelector('.ps-docs-sidebar');
if (!docsBody || !tocList) {
return;
}
const headings = docsBody.querySelectorAll('h2');
if (headings.length === 0) {
if (sidebar) { sidebar.style.display = 'none'; }
return;
}
/**
* Deterministic slug derived from heading text. Collisions resolved
* with a numeric suffix so every h2 gets a unique ID even when authors
* repeat titles ("Examples", "Examples", ...).
* @param {string} text
* @returns {string}
*/
function slugify(text) {
return String(text)
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '') || 'section';
}
function buildToc() {
const used = Object.create(null);
headings.forEach(function (heading) {
if (!heading.id) {
let base = slugify(heading.textContent || '');
let slug = base;
let n = 2;
while (document.getElementById(slug) || used[slug]) {
slug = base + '-' + n;
n++;
}
heading.id = slug;
used[slug] = true;
}
const li = document.createElement('li');
const link = document.createElement('a');
link.href = '#' + heading.id;
link.textContent = heading.textContent;
link.className = 'ps-docs-toc-link';
link.addEventListener('click', function (e) {
e.preventDefault();
smoothScrollTo(heading);
});
li.appendChild(link);
tocList.appendChild(li);
});
}
function smoothScrollTo(target) {
const headerEl = document.querySelector('.site-header');
const headerHeight = headerEl ? headerEl.offsetHeight : 0;
const offset = 24;
const top = target.getBoundingClientRect().top + window.pageYOffset - headerHeight - offset;
window.scrollTo({ top: top, behavior: 'smooth' });
history.replaceState(null, '', '#' + target.id);
}
function initScrollSpy() {
const tocLinks = tocList.querySelectorAll('.ps-docs-toc-link');
if (tocLinks.length === 0) return;
const headerEl = document.querySelector('.site-header');
const headerHeight = headerEl ? headerEl.offsetHeight : 0;
const observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (!entry.isIntersecting) return;
const id = entry.target.id;
tocLinks.forEach(function (link) {
link.classList.remove('ps-docs-toc-link--active');
if (link.getAttribute('href') === '#' + id) {
link.classList.add('ps-docs-toc-link--active');
}
});
});
}, {
rootMargin: '-' + (headerHeight + 32) + 'px 0px -60% 0px',
threshold: 0
});
headings.forEach(function (heading) { observer.observe(heading); });
}
function initMobileToggle() {
const tocTitle = document.querySelector('.ps-docs-toc-title');
if (!tocTitle || !sidebar) return;
tocTitle.addEventListener('click', function () {
if (window.innerWidth < 1024) {
sidebar.classList.toggle('ps-docs-sidebar--open');
}
});
}
buildToc();
initScrollSpy();
initMobileToggle();
})();