koajs / ratelimit

Rate limiter middleware
MIT License
485 stars 57 forks source link

Property "max" expected behaviour #56

Closed jorgellose closed 4 years ago

jorgellose commented 4 years ago

Node version: 13.0.1 koa-ratelimit version: 4.3.0 koa version: 2.11.0

Tested from localhost with alias => example.com => 127.0.0.1

For me the expected behavior would be that every 60 seconds I can only send two requests. However, only the third request is blocking me every 60 seconds, (max + 1 request). The same thing happens with 10, 100 ...

If i console.log db for my ip it has negative remaining values for > max

const db = new Map(); app.use( rateLimit({ driver: 'memory', db: db, duration: 60000, errorMessage: 'rate limit exceded', id: (ctx) => ctx.ip, headers: { remaining: 'Rate-Limit-Remaining', reset: 'Rate-Limit-Reset', total: 'Rate-Limit-Total' }, max: 2, disableHeader: true, whitelist: (ctx) => { }, blacklist: (ctx) => { } }) );

jorgellose commented 4 years ago

I think the problem is on index.js:103 if (limit.remaining) return await next(); to if (limit.remaining > 0) return await next();

solves it

(maybe the problem is in memory.js:91 allowing you to have negative remainings)

jorgellose commented 4 years ago

Okey i was 14h late, https://github.com/koajs/ratelimit/pull/55/commits/a622a5a6a3494f3000adcd416e476e6ef8d1aa61