about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@fakecake.org>2026-06-21 12:20:40 +0300
committerAndrew Dolgov <fox@fakecake.org>2026-06-21 12:20:40 +0300
commit39062a27ce241bb0b8a1151e7aa73673e0fd6443 (patch)
tree92492ff532908d056be69028ed3b61e40ac7781f
parent7edf66a0b06a9764084ef426e53eaa28d7bd4ade (diff)
downloadthe-epube-39062a27ce241bb0b8a1151e7aa73673e0fd6443.tar.gz
the-epube-39062a27ce241bb0b8a1151e7aa73673e0fd6443.tar.xz
add basic rate-limiting for login
-rw-r--r--backend.php1
-rw-r--r--classes/RateLimitMiddleware.php119
-rw-r--r--login.php6
3 files changed, 124 insertions, 2 deletions
diff --git a/backend.php b/backend.php
index 07405de..2c43dad 100644
--- a/backend.php
+++ b/backend.php
@@ -13,6 +13,7 @@
 
 	$router = new Router();
 	$router->addMiddleware(new CsrfMiddleware());
+	$router->addMiddleware(new RateLimitMiddleware());
 
 	$router->addRoute("perform-login", new \Handler\LoginHandler());
 	$router->addRoute("perform-oidc-login", new \Handler\LoginHandler());
diff --git a/classes/RateLimitMiddleware.php b/classes/RateLimitMiddleware.php
new file mode 100644
index 0000000..564fc50
--- /dev/null
+++ b/classes/RateLimitMiddleware.php
@@ -0,0 +1,119 @@
+<?php
+
+class RateLimitMiddleware implements MiddlewareInterface
+{
+    /** @var list<string> */
+    private array $loginOps;
+
+    private int $maxAttempts;
+    private int $windowSeconds;
+    private int $lockoutBase;
+    private int $lockoutMax;
+    private string $ip;
+    private bool $enabled;
+
+    /**
+     * @param list<string> $loginOps  Operations to protect (default: ['perform-login'])
+     * @param int $maxAttempts        Max attempts within the window
+     * @param int $windowSeconds      Sliding window size in seconds
+     * @param int $lockoutBase        Initial lockout duration in seconds
+     * @param int $lockoutMax         Maximum lockout duration (cap) in seconds
+     */
+    public function __construct(
+        array $loginOps = ['perform-login'],
+        int $maxAttempts = 5,
+        int $windowSeconds = 300,
+        int $lockoutBase = 60,
+        int $lockoutMax = 1800
+    ) {
+        $this->loginOps       = $loginOps;
+        $this->maxAttempts    = $maxAttempts;
+        $this->windowSeconds  = $windowSeconds;
+        $this->lockoutBase    = $lockoutBase;
+        $this->lockoutMax     = $lockoutMax;
+        $this->ip             = $this->getClientIp();
+        $this->enabled        = $this->isApcuAvailable();
+    }
+
+    public function process(Request $request, callable $next): Response
+    {
+        $op = $request->getString('op', '');
+
+        // Only apply to login endpoints
+        if (!in_array($op, $this->loginOps, true)) {
+            return $next($request);
+        }
+
+        // Graceful degradation — never block legitimate users
+        if (!$this->enabled) {
+            return $next($request);
+        }
+
+        // Check for active lockout
+        $lockKey    = "epube_rl_lock_{$this->ip}";
+        $remaining  = apcu_fetch($lockKey, $lockSuccess);
+        if ($lockSuccess && is_int($remaining) && $remaining > 0) {
+            return $this->lockedOutResponse($remaining);
+        }
+        if ($lockSuccess) {
+            apcu_delete($lockKey);
+        }
+
+        // Check sliding window of attempts
+        $windowKey = "epube_rl_win_{$this->ip}";
+        $now       = time();
+        $cutoff    = $now - $this->windowSeconds;
+
+        $attempts = apcu_fetch($windowKey, $winSuccess);
+        if (!$winSuccess || !is_array($attempts)) {
+            $attempts = [];
+        }
+
+        // Prune expired entries
+        $attempts = array_values(array_filter(
+            $attempts,
+            static fn($t): bool => is_int($t) && $t > $cutoff
+        ));
+
+        if (count($attempts) >= $this->maxAttempts) {
+            $excess      = count($attempts) - $this->maxAttempts;
+            $lockoutDur  = min(
+                $this->lockoutBase * pow(2, $excess),
+                $this->lockoutMax
+            );
+            apcu_store($lockKey, $lockoutDur, $lockoutDur);
+            return $this->lockedOutResponse($lockoutDur);
+        }
+
+        // Record this attempt
+        $attempts[] = $now;
+        apcu_store($windowKey, $attempts, $this->windowSeconds);
+
+        return $next($request);
+    }
+
+    private function lockedOutResponse(int $remaining): Response
+    {
+        return (new Response())
+            ->withStatus(429)
+            ->withHeader('Retry-After', (string) $remaining)
+            ->withBody(json_encode([
+                'error' => "Too many login attempts. Try again in {$remaining}s.",
+            ]));
+    }
+
+    private function getClientIp(): string
+    {
+        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
+            $ips = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
+            return $ips[0];
+        }
+
+        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
+    }
+
+    private function isApcuAvailable(): bool
+    {
+        return function_exists('apcu_enabled') && apcu_enabled();
+    }
+}
diff --git a/login.php b/login.php
index 5b0f10a..8fb3aa7 100644
--- a/login.php
+++ b/login.php
@@ -58,8 +58,10 @@
 									$("#login_notice").text(response.error || "Login failed.").show();
 								}
 							},
-							error: () => {
-								$("#login_notice").text("Server error. Please try again.").show();
+							error: (response) => {
+                                console.log(response);
+
+								$("#login_notice").text(response.responseJSON?.error ?? `Server error ${response.status}. Please try again.`).show();
 							}
 						});
 					});