From 898b52edcb47bcb3e9d6106e74ca73e74ea01e70 Mon Sep 17 00:00:00 2001 From: sillylaird Date: Thu, 3 Sep 2026 00:33:59 +0000 Subject: import live www.sillylaird.ca webroot --- partials/proxy_helpers.php | 80 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 partials/proxy_helpers.php (limited to 'partials/proxy_helpers.php') diff --git a/partials/proxy_helpers.php b/partials/proxy_helpers.php new file mode 100644 index 0000000..59ac3cb --- /dev/null +++ b/partials/proxy_helpers.php @@ -0,0 +1,80 @@ + deny + foreach ($ips as $ip) { + $ok = filter_var( + $ip, + FILTER_VALIDATE_IP, + FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE + ); + if ($ok === false) return false; + } + return true; + } +} + +if (!function_exists('proxy_rate_limit')) { + /** + * Returns true if the request is allowed. Uses a tiny file per + * (endpoint, client IP) holding recent unix timestamps. + */ + function proxy_rate_limit(string $endpoint, int $max = 30, int $windowSec = 60): bool { + $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; + $key = preg_replace('/[^A-Za-z0-9._-]/', '_', $endpoint . '_' . $ip); + $dir = sys_get_temp_dir() . '/sillylaird_ratelimit'; + if (!is_dir($dir)) @mkdir($dir, 0700, true); + $file = $dir . '/' . $key; + + $now = time(); + $cutoff = $now - $windowSec; + + $fp = @fopen($file, 'c+'); + if (!$fp) return true; // fail-open: don't block legit traffic on disk error + try { + flock($fp, LOCK_EX); + $data = stream_get_contents($fp); + $stamps = $data === '' ? [] : array_map('intval', explode("\n", trim($data))); + $stamps = array_values(array_filter($stamps, fn($t) => $t >= $cutoff)); + if (count($stamps) >= $max) { + return false; + } + $stamps[] = $now; + ftruncate($fp, 0); + rewind($fp); + fwrite($fp, implode("\n", $stamps)); + return true; + } finally { + flock($fp, LOCK_UN); + fclose($fp); + } + } +} -- cgit v1.2.3