1.0.0 • Published 3 years ago

@justpsst/iprequestlimiter v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

Documentation

Description

Middleware for limiting requests by route. It's designed for ExpressJS and uses Redis as storage.

Installation

npm install --save @justpsst/iprequestlimiter

Usage

import { ipLimiter } from '@justpsst/iprequestlimiter';

router.get('/', ipLimiter(config), (request, response) => {...});

Config interface

PropertyTypeDefaultDescription
delaysnumber[], optional10, 20, 30, 40, 50, 60Delay between requests in seconds. In case when request comes before delay timer expires, delay timer would be increased (10 > 20 > 30 ...)
storeKeystring, optional"ipLimiter"Key for redis to identify request. In redis it would be stored like ${storeKey}_${path}_${clientIp}
increaseByLimitReachednumber, optional0Number of seconds, which would be added to delay timer in case when 'delays' array reaches it's limit
redisOptionsredis.ClientOpts, optional{}Redis options described here: https://www.npmjs.com/package/redis
freeAttemptsnumber, optional0Number of free attempts, when delay timer won't be used
freeAttemptsUnlockDelaynumber, optional0Number of seconds, which is needed to refresh attemptsLeft

Behavior

When a request comes to a server, middleware checks free attempts left. Middleware modifies request object when free attempts are greater than 0 or delay timer is expired/not set up.

Object.assign(request, { delay: requestLimitInfo });

requestLimitInfo interface

PropertyTypeDescription
delaynumberDelay until next request in seconds
attemptsLeftnumberFree attempts left. Delay timer will be 0 in case when attemptsLeft is greater than 0
nextRequestTimestring, optionalTime in ISO string format. It describes the time when the delay timer will be refreshed. In case when request comes before delay timer expires, delay timer would be increased (10 > 20 > 30 ...)
freeAttemptsUnlockTimestring, optionalTime in ISO string format. It describes the time when the freeAttempts will be refreshed. In case when request comes before unlock timer releases, free attempts would be decreased by 1
{
  delay: number,
  attemptsLeft: number,
  nextRequestTime?: string,
  freeAttemptsUnlockTime?: string
}

In case when delay timer is not expired, the server will return the error code '429' with the response object.

return responce.status(429).send(requestLimitInfo);