Files
madar/app/Security/RateLimiter.php
T
2026-09-05 15:54:33 +03:30

52 lines
2.0 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Security;
use App\Http\HttpException;
final class RateLimiter
{
public function __construct(private readonly string $file)
{
}
/** One bounded, locked file avoids session-reset bypass and unlimited file creation. */
public function hit(string $key, int $limit, int $window): void
{
$handle = @fopen($this->file, 'c+');
if (!$handle || !flock($handle, LOCK_EX)) {
throw new HttpException('ذخیره‌سازی امن سرور در دسترس نیست.', 503);
}
try {
@chmod($this->file, 0600);
$rawState = stream_get_contents($handle);
$state = $rawState === '' ? [] : json_decode($rawState, true, 32, JSON_THROW_ON_ERROR);
if (!is_array($state)) {
throw new HttpException('ذخیره‌سازی امن سرور معتبر نیست.', 503);
}
$now = time();
foreach ($state as $entry => $bucket) {
if (($bucket['expires'] ?? 0) <= $now) {
unset($state[$entry]);
}
}
$key = hash('sha256', $key);
$bucket = $state[$key] ?? ['count' => 0, 'expires' => $now + $window];
if ($bucket['count'] >= $limit || (!isset($state[$key]) && count($state) >= 10000)) {
throw new HttpException('تعداد درخواست‌ها زیاد است؛ کمی بعد دوباره تلاش کنید.', 429);
}
$bucket['count']++;
$state[$key] = $bucket;
$json = json_encode($state, JSON_THROW_ON_ERROR);
rewind($handle);
if (!ftruncate($handle, 0) || fwrite($handle, $json) !== strlen($json) || !fflush($handle)) {
throw new HttpException('ذخیره‌سازی امن سرور در دسترس نیست.', 503);
}
} finally {
flock($handle, LOCK_UN);
fclose($handle);
}
}
}