valeriansaliou / node-fast-ratelimit

:umbrella: Fast and efficient in-memory rate-limit for Node, used to alleviate most common DOS attacks.
https://www.npmjs.com/package/fast-ratelimit
MIT License
107 stars 18 forks source link

Check without consume #7

Closed RomainLK closed 6 years ago

RomainLK commented 6 years ago

I have a use case which I wonder if it would be accepted for this library, as a PR.

Basically, I would like to use this as ratelimit against password bruteforce.

I have a route which is protected by API key. What I want is that, if the the client is properly authenticated, then the request doesn't count in the ratelimit. If the key is wrong, it counts.

Implementation for such scheme right now is:

const valid = validateApiKey()
if (!valid) {
  if (limiter.consumeSync('user')) {
    throw new Error('Invalid key')
  } else {
    throw new Error('Brute force attempt')
  }
}

Problem is that this doesn't block the bruteforce. Even if there is no more token, attacker can continue to bruteforce and he will get access to the API when he gets the right key.

What I need is a function which can check that there are available tokens, without consuming them.

if( !limiter.hasTokensSync('user')){
  throw new Error('Brute force attempt')
}
const valid = validateApiKey()
if (!valid) {
  if (limiter.consumeSync('user')) {
    throw new Error('Invalid key')
  } else {
    throw new Error('Brute force attempt')
  }
}

Would you accept a PR to support this use case?

valeriansaliou commented 6 years ago

Sounds like a valid use case for this library. PRs accepted 😄

valeriansaliou commented 6 years ago

Check: https://github.com/valeriansaliou/node-fast-ratelimit/blob/master/lib/fast_ratelimit.js#L57 this would be quite similar, w/o the "put" thing at the end.

valeriansaliou commented 6 years ago

Published in v2.2.0.