Files
MalinandClaude Opus 5.5 73229cb321 feat: standalone ITK form guard for non-WordPress forms
The honeypot/timing/content checks of ITK_Honeypot plus honeypot.es
reporting, as one dependency-free PHP file to vendor next to a static
site's mail endpoint (first users: malin.ro, roxi.es).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:06:31 +01:00

141 lines
5.9 KiB
PHP

<?php
/**
* ITK Form Guard: InformatiQ Toolkit's form spam checks (ITK_Honeypot) for
* sites that are not WordPress, e.g. a static/Astro site whose form posts to
* a small PHP mailer. One file, no dependencies; copy it next to the
* endpoint and keep this repo as the source.
*
* The form needs two extra fields:
* <input type="hidden" name="ts" value=""> Date.now() from the page's JS
* <input type="text" name="website" tabindex="-1"> trap, hidden with CSS
* and the JS should set ts on load and again on the first focusin inside the
* form (a tab left open past max_ms would fail otherwise).
*
* Usage, before any other validation:
*
* require __DIR__ . '/_itk-form-guard.php';
* $guard = new ItkFormGuard(['site' => 'https://example.es', 'log_dir' => '/var/db/x',
* 'hp_api_url' => ..., 'hp_api_token' => ...]);
* if ($block = $guard->check()) {
* // answer first: fake success when $block['pretend'], the error page otherwise
* ...send the response, fastcgi_finish_request()...
* $guard->record($block); // log + honeypot.es, after the visitor has the answer
* exit;
* }
*
* Rules, as ITK_Honeypot::check_honeypot() and check_comment_content():
* - ts missing: the request was built against the endpoint without loading
* the form. Not pretended: a real visitor without JavaScript lands on the
* error page, which should offer an email address.
* - trap filled, faster than min_ms, slower than max_ms, a URL in the email
* field, more than max_links links in the message: pretended success.
*/
declare(strict_types=1);
if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) {
http_response_code(404);
exit;
}
final class ItkFormGuard
{
private array $o;
public function __construct(array $options)
{
$this->o = $options + [
'site' => '',
'form' => 'contact',
'ts' => 'ts',
'trap' => 'website',
'email' => 'email',
'message' => 'message',
'min_ms' => 3000,
'max_ms' => 7200000,
'max_links' => 2,
'log_dir' => null,
'hp_api_url' => null,
'hp_api_token' => null,
];
}
/** null when the submission passes, else ['reason' => string, 'pretend' => bool]. */
public function check(): ?array
{
$post = static fn(string $k): string => trim((string)($_POST[$k] ?? ''));
$ts = $post($this->o['ts']);
if (!preg_match('/^\d{10,16}$/', $ts)) { // not ctype_digit(): the ctype extension isn't everywhere
return ['reason' => 'Missing timing field (form not loaded)', 'pretend' => false];
}
if ($post($this->o['trap']) !== '') {
return ['reason' => 'Honeypot field filled', 'pretend' => true];
}
$elapsed = (int)(microtime(true) * 1000) - (int)$ts;
if ($elapsed < $this->o['min_ms']) {
return ['reason' => 'Submitted too fast (' . intdiv(max(0, $elapsed), 1000) . 's)', 'pretend' => true];
}
if ($elapsed > $this->o['max_ms']) {
return ['reason' => 'Submitted too slow (' . intdiv($elapsed, 1000) . 's)', 'pretend' => true];
}
$email = $post($this->o['email']);
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)
&& preg_match('#(https?://|[a-z0-9-]+\.[a-z]{2,}/|[?&]ref=)#i', $email)) {
return ['reason' => 'URL in email field', 'pretend' => true];
}
$max = (int)$this->o['max_links'];
if ($max > 0 && preg_match_all('#https?://\S+#i', $post($this->o['message'])) > $max) {
return ['reason' => 'Too many URLs in message', 'pretend' => true];
}
return null;
}
/**
* Appends the block to <log_dir>/blocked.jsonl and reports it to
* honeypot.es (same payload as ITK_HP_API::flush()). Public client IPs
* only, so a test from inside the network never reaches the shared list.
* Call it after the response is out: the report can take a few seconds.
*/
public function record(array $block): void
{
$ip = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$ua = mb_substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 300);
if ($this->o['log_dir']) {
$line = json_encode([
'time' => date('c'), 'ip' => $ip, 'form' => $this->o['form'], 'reason' => $block['reason'], 'ua' => $ua,
'email' => mb_substr((string)($_POST[$this->o['email']] ?? ''), 0, 200),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
@file_put_contents(rtrim($this->o['log_dir'], '/') . '/blocked.jsonl', $line . "\n", FILE_APPEND | LOCK_EX);
}
$public = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
if (!$public || empty($this->o['hp_api_url']) || !function_exists('curl_init')) {
return;
}
$ch = curl_init(rtrim((string)$this->o['hp_api_url'], '/') . '/api/v1/submit');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_HTTPHEADER => array_values(array_filter([
'Content-Type: application/json',
!empty($this->o['hp_api_token']) ? 'Authorization: Bearer ' . $this->o['hp_api_token'] : null,
])),
CURLOPT_POSTFIELDS => json_encode([
'site_hash' => hash('sha256', (string)$this->o['site']),
'blocks' => [[
'ip' => $ip,
'form_type' => $this->o['form'],
'reason' => $block['reason'],
'user_agent' => $ua,
'blocked_at' => date('Y-m-d H:i:s'),
]],
]),
]);
curl_exec($ch);
curl_close($ch);
}
}