Skip to content

Commit 854dc35

Browse files
committed
fix(rate-limiter): prevent TTL reset on every request in sliding window
1 parent b6ca706 commit 854dc35

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

lib/rate-limit.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,15 @@ export class RateLimiter {
4848
* }
4949
*/
5050
check(ip: string): boolean {
51-
if (this.allowlist.has(ip)) return true; // for check()
52-
if (this.blocklist.has(ip)) return false; // for check()
53-
const current = this.cache.get(ip) || 0;
54-
if (current >= this.limit) {
55-
return false;
51+
if (this.allowlist.has(ip)) return true;
52+
if (this.blocklist.has(ip)) return false;
53+
const current = this.cache.get(ip) ?? 0;
54+
if (current >= this.limit) return false;
55+
if (current === 0) {
56+
this.cache.set(ip, 1, this.windowMs);
57+
} else {
58+
this.cache.set(ip, current + 1, this.windowMs);
5659
}
57-
this.cache.set(ip, current + 1, this.windowMs);
5860
return true;
5961
}
6062
checkWithResult(ip: string): RateLimitResult {
@@ -79,7 +81,11 @@ export class RateLimiter {
7981
};
8082
}
8183

82-
this.cache.set(ip, current + 1, this.windowMs);
84+
if (current === 0) {
85+
this.cache.set(ip, 1, this.windowMs);
86+
} else {
87+
this.cache.set(ip, current + 1, this.windowMs);
88+
}
8389
return {
8490
success: true,
8591
limit: this.limit,

0 commit comments

Comments
 (0)