Block bot registrations and add cron cleanup for unconfirmed accounts

register.php was a fully open signup form with no bot defenses — the
likely source of the unconfirmed accounts piling up in admin/users.php.

- Add an always-on honeypot field + timing trap to register.php: either
  tripping silently pretends success without creating an account, so a
  bot doesn't learn it was caught. No configuration needed.

- Add optional Google reCAPTCHA v3 support (includes/recaptcha.php,
  recaptcha_enabled()/verify_recaptcha(), no Composer dependency — a
  raw file_get_contents() POST like mailer.php's SMTP socket approach).
  A failed check here shows a real, visible error instead of the silent
  honeypot path, since a legitimate low-score user deserves a retry.

- Configure it through admin/settings.php's new "Bot Protection" section,
  mirroring the existing SMTP pattern exactly: recaptcha_enabled/
  recaptcha_site_key/recaptcha_secret_key in site_settings, secret key
  masked the same way smtp_pass now is (blank submission keeps it
  unchanged). install.php seeds sane defaults so the feature stays off
  until explicitly configured — fully backward compatible.

- Add cron/cleanup_unconfirmed.php: deletes accounts still unconfirmed
  after 3 days. CLI-only (refuses to run over HTTP, and cron/.htaccess
  denies web access to the directory as a second layer) since it's an
  unattended, irreversible deletion. Safe by construction — login.php
  already refuses login to unconfirmed accounts, so these rows can never
  own a session/novena_group/custom_prayer row. Not wired up
  automatically; README documents the Hostinger cron job to schedule it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-15 10:11:29 -07:00
parent 9622f9aeca
commit c7f1bdd630
7 changed files with 301 additions and 73 deletions
+17
View File
@@ -64,6 +64,20 @@ chmod 755 uploads/
Configure outbound email in **Admin → Settings** for registration confirmation and password reset emails. If left blank, the app will auto-confirm new users instead. Configure outbound email in **Admin → Settings** for registration confirmation and password reset emails. If left blank, the app will auto-confirm new users instead.
### 6. Bot protection (optional)
`register.php` always runs a built-in honeypot + timing trap against scripted signups — no setup needed. On top of that, you can enable Google reCAPTCHA v3: register your domain at [google.com/recaptcha](https://www.google.com/recaptcha/admin) (choose **reCAPTCHA v3**), then enter the Site Key and Secret Key in **Admin → Settings → Bot Protection**.
### 7. Scheduled cleanup of unconfirmed accounts (optional)
`cron/cleanup_unconfirmed.php` permanently deletes accounts that are still unconfirmed 3 days after registering — useful for clearing out bot signups that get past the defenses above. It's CLI-only (refuses to run over HTTP) and is not wired up automatically; schedule it yourself as a cron job. In Hostinger's hPanel: **Advanced → Cron Jobs** → run daily:
```bash
php /home/<your-account>/domains/loveandrosary.com/public_html/cron/cleanup_unconfirmed.php
```
(Adjust the path to match your actual hosting account.) Confirmed accounts are never touched — only rows with `email_confirmed = 0`.
## Upgrading an Existing Install ## Upgrading an Existing Install
`schema.sql` reflects the current database structure. For a production database that predates the `failed_login_attempts` / `locked_until` login-lockout columns, run this once against it manually — it's not applied automatically since there's no migration runner against a live database: `schema.sql` reflects the current database structure. For a production database that predates the `failed_login_attempts` / `locked_until` login-lockout columns, run this once against it manually — it's not applied automatically since there's no migration runner against a live database:
@@ -101,11 +115,14 @@ Rosary/
├── config/ ├── config/
│ ├── db.example.php # Copy → db.php and fill in credentials │ ├── db.example.php # Copy → db.php and fill in credentials
│ └── db.php # (gitignored — contains real credentials) │ └── db.php # (gitignored — contains real credentials)
├── cron/
│ └── cleanup_unconfirmed.php # CLI-only; schedule via host cron
├── data/ ├── data/
│ └── prayers.php # All prayer text + build_decade_slides() │ └── prayers.php # All prayer text + build_decade_slides()
├── includes/ ├── includes/
│ ├── auth.php # require_auth(), current_user(), has_role(), login lockout │ ├── auth.php # require_auth(), current_user(), has_role(), login lockout
│ ├── csrf.php # csrf_token(), csrf_field(), csrf_verify() │ ├── csrf.php # csrf_token(), csrf_field(), csrf_verify()
│ ├── recaptcha.php # recaptcha_enabled(), verify_recaptcha()
│ ├── build_slides.php │ ├── build_slides.php
│ ├── donate.php │ ├── donate.php
│ └── mailer.php │ └── mailer.php
+67 -4
View File
@@ -6,6 +6,7 @@ require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php'; require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/mailer.php'; require_once __DIR__ . '/../includes/mailer.php';
require_once __DIR__ . '/../includes/csrf.php'; require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/recaptcha.php';
require_role('superadmin'); require_role('superadmin');
@@ -20,19 +21,27 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? 'save'; $action = $_POST['action'] ?? 'save';
if ($action === 'save') { if ($action === 'save') {
// smtp_pass is handled separately: the form always renders it blank // smtp_pass and recaptcha_secret_key are handled separately below:
// (see below), so a blank submission means "leave it unchanged", // the form always renders them blank, so a blank submission means
// not "clear it". // "leave it unchanged", not "clear it".
$keys = ['site_name','site_url','smtp_host','smtp_port','smtp_user','smtp_from','smtp_from_name', $keys = ['site_name','site_url','smtp_host','smtp_port','smtp_user','smtp_from','smtp_from_name',
'donate_enabled','donate_type','donate_handle','donate_label']; 'donate_enabled','donate_type','donate_handle','donate_label',
'recaptcha_enabled','recaptcha_site_key'];
// Checkboxes are absent from $_POST entirely when unchecked.
$checkbox_keys = ['donate_enabled', 'recaptcha_enabled'];
foreach ($keys as $k) { foreach ($keys as $k) {
if (isset($_POST[$k])) { if (isset($_POST[$k])) {
set_setting($k, trim($_POST[$k])); set_setting($k, trim($_POST[$k]));
} elseif (in_array($k, $checkbox_keys, true)) {
set_setting($k, '0');
} }
} }
if (!empty($_POST['smtp_pass'])) { if (!empty($_POST['smtp_pass'])) {
set_setting('smtp_pass', trim($_POST['smtp_pass'])); set_setting('smtp_pass', trim($_POST['smtp_pass']));
} }
if (!empty($_POST['recaptcha_secret_key'])) {
set_setting('recaptcha_secret_key', trim($_POST['recaptcha_secret_key']));
}
$message = 'Settings saved.'; $message = 'Settings saved.';
$site_name = get_setting('site_name', APP_NAME); // refresh $site_name = get_setting('site_name', APP_NAME); // refresh
} }
@@ -68,6 +77,9 @@ $settings = [
'donate_type' => get_setting('donate_type', 'custom'), 'donate_type' => get_setting('donate_type', 'custom'),
'donate_handle' => get_setting('donate_handle', ''), 'donate_handle' => get_setting('donate_handle', ''),
'donate_label' => get_setting('donate_label', ''), 'donate_label' => get_setting('donate_label', ''),
'recaptcha_enabled' => get_setting('recaptcha_enabled', '0'),
'recaptcha_site_key' => get_setting('recaptcha_site_key', ''),
'recaptcha_secret_key_set' => get_setting('recaptcha_secret_key') !== '',
]; ];
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
@@ -226,6 +238,45 @@ $settings = [
</div> </div>
</div> </div>
<div class="settings-section">
<h3>Bot Protection (reCAPTCHA)</h3>
<p class="help-text" style="margin-top:0;margin-bottom:20px">
Adds invisible Google reCAPTCHA v3 to the registration form, on top of the built-in
honeypot/timing checks. Register your domain at
<a href="https://www.google.com/recaptcha/admin" target="_blank" rel="noopener">google.com/recaptcha</a>
(choose reCAPTCHA v3) to get a Site Key and Secret Key.
</p>
<div class="form-group">
<label style="display:flex;align-items:center;gap:10px;cursor:pointer">
<input type="checkbox" name="recaptcha_enabled" value="1"
id="recaptcha_enabled"
<?= $settings['recaptcha_enabled'] === '1' ? 'checked' : '' ?>
style="width:18px;height:18px">
<span>Enable reCAPTCHA on registration</span>
</label>
</div>
<div class="form-grid">
<div class="form-group">
<label for="recaptcha_site_key">Site Key</label>
<input type="text" id="recaptcha_site_key" name="recaptcha_site_key"
autocomplete="off"
value="<?= htmlspecialchars($settings['recaptcha_site_key']) ?>">
</div>
<div class="form-group">
<label for="recaptcha_secret_key">Secret Key</label>
<div class="pass-wrap">
<input type="password" id="recaptcha_secret_key" name="recaptcha_secret_key"
autocomplete="new-password"
placeholder="<?= $settings['recaptcha_secret_key_set'] ? '•••••••• (leave blank to keep current)' : '' ?>">
<button type="button" class="pass-toggle" onclick="toggleRecaptchaSecret()">Show</button>
</div>
<p class="help-text">
<?= $settings['recaptcha_secret_key_set'] ? '&#x2713; A secret key is currently set. Leave blank to keep it.' : 'No secret key set.' ?>
</p>
</div>
</div>
</div>
<div class="form-actions"> <div class="form-actions">
<button type="submit" class="btn btn-primary">Save Settings</button> <button type="submit" class="btn btn-primary">Save Settings</button>
</div> </div>
@@ -270,6 +321,18 @@ function togglePass() {
btn.textContent = 'Show'; btn.textContent = 'Show';
} }
} }
function toggleRecaptchaSecret() {
var inp = document.getElementById('recaptcha_secret_key');
var btn = inp.nextElementSibling;
if (inp.type === 'password') {
inp.type = 'text';
btn.textContent = 'Hide';
} else {
inp.type = 'password';
btn.textContent = 'Show';
}
}
</script> </script>
</body> </body>
</html> </html>
+5
View File
@@ -0,0 +1,5 @@
# Defense in depth: cron/cleanup_unconfirmed.php already refuses to run
# outside the CLI, but block web access to this directory entirely too.
Require all denied
Order allow,deny
Deny from all
+41
View File
@@ -0,0 +1,41 @@
<?php
/**
* cron/cleanup_unconfirmed.php
* Deletes accounts that have sat unconfirmed for more than $days days.
*
* CLI-only — refuses to run if reached over HTTP, since this performs a
* real, irreversible deletion and has no business being web-accessible.
*
* Schedule this via your host's cron job feature, e.g. once daily:
* php /path/to/Rosary/cron/cleanup_unconfirmed.php
*
* Safe by construction: login.php refuses login to any account with
* email_confirmed = 0, so an unconfirmed account can never have created a
* session/novena_group/custom_prayer row — nothing here can orphan data.
*/
if (PHP_SAPI !== 'cli') {
http_response_code(403);
exit('This script may only be run from the command line.');
}
require_once __DIR__ . '/../config/db.php';
$days = 3;
$pdo = get_pdo();
$st = $pdo->prepare("
SELECT id, username, email, created_at
FROM users
WHERE email_confirmed = 0
AND created_at < (NOW() - INTERVAL ? DAY)
");
$st->execute([$days]);
$stale = $st->fetchAll();
$del = $pdo->prepare('DELETE FROM users WHERE id = ?');
foreach ($stale as $u) {
$del->execute([$u['id']]);
echo date('c') . " deleted unconfirmed user #{$u['id']} ({$u['username']}, {$u['email']}, registered {$u['created_at']})\n";
}
echo date('c') . ' — ' . count($stale) . " account(s) removed.\n";
+48
View File
@@ -0,0 +1,48 @@
<?php
/**
* includes/recaptcha.php — Google reCAPTCHA v3 verification.
* No Composer dependency: uses file_get_contents() with a POST stream context,
* matching the no-dependency style of includes/mailer.php.
*/
/** True if reCAPTCHA is turned on and a site key is configured. */
function recaptcha_enabled(): bool {
return get_setting('recaptcha_enabled', '0') === '1' && get_setting('recaptcha_site_key') !== '';
}
/**
* Verify a reCAPTCHA v3 token against Google's siteverify endpoint.
* Returns true only if the request succeeded and the score meets $min_score.
*/
function verify_recaptcha(string $token, float $min_score = 0.5): bool {
$secret = get_setting('recaptcha_secret_key');
if ($secret === '' || $token === '') return false;
$post_data = http_build_query([
'secret' => $secret,
'response' => $token,
'remoteip' => $_SERVER['REMOTE_ADDR'] ?? '',
]);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => $post_data,
'timeout' => 10,
],
]);
try {
$response = @file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
if ($response === false) return false;
$result = json_decode($response, true);
if (!is_array($result)) return false;
return !empty($result['success']) && (float)($result['score'] ?? 0) >= $min_score;
} catch (Throwable $e) {
error_log('reCAPTCHA verify error: ' . $e->getMessage());
return false;
}
}
+3
View File
@@ -133,6 +133,9 @@ $defaults = [
'smtp_from_name' => 'Rosary Presenter', 'smtp_from_name' => 'Rosary Presenter',
'site_name' => 'Rosary Presenter', 'site_name' => 'Rosary Presenter',
'site_url' => '', 'site_url' => '',
'recaptcha_enabled' => '0',
'recaptcha_site_key' => '',
'recaptcha_secret_key' => '',
]; ];
$ins_setting = $pdo->prepare('INSERT IGNORE INTO site_settings (key_name, val) VALUES (?, ?)'); $ins_setting = $pdo->prepare('INSERT IGNORE INTO site_settings (key_name, val) VALUES (?, ?)');
foreach ($defaults as $k => $v) { foreach ($defaults as $k => $v) {
+55 -4
View File
@@ -3,6 +3,7 @@ require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/includes/auth.php'; require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/mailer.php'; require_once __DIR__ . '/includes/mailer.php';
require_once __DIR__ . '/includes/csrf.php'; require_once __DIR__ . '/includes/csrf.php';
require_once __DIR__ . '/includes/recaptcha.php';
_auth_start(); _auth_start();
@@ -18,6 +19,16 @@ $fields = ['username' => '', 'display_name' => '', 'email' => ''];
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER['REQUEST_METHOD'] === 'POST') {
csrf_verify(); csrf_verify();
// Honeypot + timing trap: a decoy field real users never see/fill, and a
// minimum time between the form being shown and submitted. Either one
// tripping means this almost certainly isn't a human — pretend success
// without creating an account, so a bot doesn't learn it was caught and
// adapt its script.
$honeypot = trim($_POST['website'] ?? '');
$shown_at = (int)($_SESSION['reg_form_shown_at'] ?? 0);
$bot_detected = ($honeypot !== '') || (time() - $shown_at < 3);
$username = trim($_POST['username'] ?? ''); $username = trim($_POST['username'] ?? '');
$display_name = trim($_POST['display_name'] ?? ''); $display_name = trim($_POST['display_name'] ?? '');
$email = trim($_POST['email'] ?? ''); $email = trim($_POST['email'] ?? '');
@@ -26,6 +37,17 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$fields = compact('username', 'display_name', 'email'); $fields = compact('username', 'display_name', 'email');
if ($bot_detected) {
$success = true;
$auto_confirmed = false;
} else {
// reCAPTCHA v3: unlike the honeypot/timing trap above, a failure here
// gets a real, visible error — a legitimate low-score user deserves
// an explicit retry rather than a silently-discarded submission.
if (recaptcha_enabled() && !verify_recaptcha($_POST['recaptcha_token'] ?? '')) {
$errors[] = 'We could not verify your submission. Please try again.';
}
// Validate username // Validate username
if (!preg_match('/^[a-zA-Z0-9_]{3,30}$/', $username)) { if (!preg_match('/^[a-zA-Z0-9_]{3,30}$/', $username)) {
$errors[] = 'Username must be 3-30 characters and contain only letters, numbers, and underscores.'; $errors[] = 'Username must be 3-30 characters and contain only letters, numbers, and underscores.';
@@ -49,9 +71,6 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$chk = $pdo->prepare('SELECT id FROM users WHERE username = ? OR email = ?'); $chk = $pdo->prepare('SELECT id FROM users WHERE username = ? OR email = ?');
$chk->execute([$username, $email]); $chk->execute([$username, $email]);
$existing = $chk->fetchAll(); $existing = $chk->fetchAll();
foreach ($existing as $row) {
// Re-check which field conflicts
}
if (!empty($existing)) { if (!empty($existing)) {
$chk_u = $pdo->prepare('SELECT id FROM users WHERE username = ?'); $chk_u = $pdo->prepare('SELECT id FROM users WHERE username = ?');
$chk_u->execute([$username]); $chk_u->execute([$username]);
@@ -98,6 +117,12 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$auto_confirmed = $auto_confirm; $auto_confirmed = $auto_confirm;
} }
} }
}
// Refresh the timing-trap timestamp whenever the form is about to be (re)shown.
if (!$success) {
$_SESSION['reg_form_shown_at'] = time();
}
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
@@ -107,6 +132,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
<link rel="icon" type="image/svg+xml" href="<?= BASE_URL ?>/favicon.svg"> <link rel="icon" type="image/svg+xml" href="<?= BASE_URL ?>/favicon.svg">
<title>Register — <?= htmlspecialchars(get_setting('site_name', APP_NAME)) ?></title> <title>Register — <?= htmlspecialchars(get_setting('site_name', APP_NAME)) ?></title>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/setup.css"> <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/setup.css">
<?php if (recaptcha_enabled()): ?>
<script src="https://www.google.com/recaptcha/api.js?render=<?= urlencode(get_setting('recaptcha_site_key')) ?>"></script>
<?php endif; ?>
</head> </head>
<body class="login-page"> <body class="login-page">
<div class="login-box" style="max-width:460px"> <div class="login-box" style="max-width:460px">
@@ -133,8 +161,15 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
</div> </div>
<?php endif; ?> <?php endif; ?>
<form method="post" action="<?= BASE_URL ?>/register"> <form method="post" action="<?= BASE_URL ?>/register" id="register-form">
<?= csrf_field() ?> <?= csrf_field() ?>
<?php if (recaptcha_enabled()): ?>
<input type="hidden" name="recaptcha_token" id="recaptcha_token">
<?php endif; ?>
<div style="position:absolute;left:-9999px;top:-9999px" aria-hidden="true">
<label for="website">Website</label>
<input type="text" id="website" name="website" tabindex="-1" autocomplete="off">
</div>
<div class="form-group"> <div class="form-group">
<label for="username">Username <span class="required">*</span></label> <label for="username">Username <span class="required">*</span></label>
<input type="text" id="username" name="username" <input type="text" id="username" name="username"
@@ -176,5 +211,21 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
<?php endif; ?> <?php endif; ?>
</div> </div>
<?php if (recaptcha_enabled()): ?>
<script>
document.getElementById('register-form').addEventListener('submit', function (e) {
e.preventDefault();
var form = this;
grecaptcha.ready(function () {
grecaptcha.execute('<?= htmlspecialchars(get_setting('recaptcha_site_key')) ?>', { action: 'register' })
.then(function (token) {
document.getElementById('recaptcha_token').value = token;
form.submit();
});
});
});
</script>
<?php endif; ?>
</body> </body>
</html> </html>