Files
pguzman 9622f9aeca Consolidate schema, add CSRF protection, and add login rate-limiting
Six fixes from a codebase review:

- Consolidate the ad hoc install.php + migrate_v2..v6.php chain into one
  canonical schema.sql (structure reference) plus a simplified install.php
  that creates all tables and seeds site_settings, the superadmin account,
  and the standard prayer library. The six migrate_v*.php scripts are
  deleted — their cumulative effect is now fully captured in schema.sql.

- Delete the two root-level setup.php/novena_group.php files that existed
  only to redirect to their admin/ equivalents of the same name; confirmed
  unreferenced by any link or .htaccess rule.

- Decouple includes/build_slides.php from data/prayers.php's implicit
  `global $opening, $mysteries, ...` contract. data/prayers.php now
  explicitly returns its arrays; build_slides.php loads them through a
  small memoized get_prayer_data() and destructures them by key.

- Add CSRF protection (includes/csrf.php: csrf_token/csrf_field/csrf_verify)
  across every POST-handling endpoint — 10 form pages and 7 API endpoints —
  plus token wiring in the JS/inline scripts that call the FormData- and
  JSON-body API endpoints (builder.js, setup.js, and the inline scripts in
  admin/audio.php, admin/novena_group.php, and index.php).

- Stop round-tripping the SMTP password in plaintext through the settings
  form: the field now renders blank with a "currently set" hint, and a
  blank submission leaves the stored password unchanged instead of
  clearing it.

- Add login rate-limiting: users.failed_login_attempts / locked_until
  columns, is_locked_out()/record_login_failure()/record_login_success()
  helpers in includes/auth.php, and lockout handling in login.php (5
  failed attempts locks the account for 15 minutes). README documents the
  one manual ALTER TABLE needed to add these columns to an existing
  production database.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-15 09:34:10 -07:00

47 lines
1.8 KiB
PHP

<?php
/**
* includes/csrf.php — per-session CSRF token generation and verification.
*/
require_once __DIR__ . '/auth.php';
/** Return the current session's CSRF token, generating one on first use. */
function csrf_token(): string {
_auth_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
/** Echo a hidden <input> carrying the CSRF token, for use inside a <form>. */
function csrf_field(): string {
return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars(csrf_token()) . '">';
}
/**
* Verify the CSRF token on the current request (checks $_POST['csrf_token'],
* falling back to the X-CSRF-Token header for JSON-body API calls). Aborts
* the request with a 403 on failure.
*/
function csrf_verify(): void {
_auth_start();
$sent = $_POST['csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
$expected = $_SESSION['csrf_token'] ?? '';
if ($sent === '' || $expected === '' || !hash_equals($expected, $sent)) {
http_response_code(403);
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
$ctype = $_SERVER['CONTENT_TYPE'] ?? '';
if (str_contains($accept, 'application/json') || str_contains($ctype, 'application/json')) {
header('Content-Type: application/json');
echo json_encode(['error' => 'Invalid or missing security token. Please refresh the page and try again.']);
} else {
echo '<!DOCTYPE html><html><body style="font-family:system-ui;max-width:500px;margin:60px auto;text-align:center">'
. '<h1 style="color:#dc2626">Security Check Failed</h1>'
. '<p>Invalid or missing security token. Please go back, refresh the page, and try again.</p>'
. '</body></html>';
}
exit;
}
}