hono-rate-limiter 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  <div align="center">
4
4
 
5
- [![tests](https://img.shields.io/github/actions/workflow/status/rhinobase/hono-rate-limiter/test.yaml)](https://github.com/rhinobase/hono-rate-limiter/actions/workflows/test.yaml)
5
+ [![tests](https://img.shields.io/github/actions/workflow/status/rhinobase/hono-rate-limiter/test.yml)](https://github.com/rhinobase/hono-rate-limiter/actions/workflows/test.yml)
6
6
  [![npm version](https://img.shields.io/npm/v/hono-rate-limiter.svg)](https://npmjs.org/package/hono-rate-limiter "View this project on NPM")
7
7
  [![npm downloads](https://img.shields.io/npm/dm/hono-rate-limiter)](https://www.npmjs.com/package/hono-rate-limiter)
8
8
  [![license](https://img.shields.io/npm/l/hono-rate-limiter)](LICENSE)
@@ -12,8 +12,8 @@
12
12
  Rate limiting middleware for [Hono](https://hono.dev/). Use to
13
13
  limit repeated requests to public APIs and/or endpoints such as password reset.
14
14
 
15
- > [!WARNING]
16
- > The `keyGenerator` function is currently under construction and needs to be defined for `hono-rate-limiter` to work properly in your environment. Please ensure that you define the `keyGenerator` function according to the documentation before using the library.
15
+ > [!NOTE]
16
+ > The `keyGenerator` function needs to be defined for `hono-rate-limiter` to work properly in your environment. Please ensure that you define the `keyGenerator` function according to the documentation before using the library.
17
17
 
18
18
  ## Usage
19
19
 
@@ -56,6 +56,11 @@ Here is a list of stores:
56
56
 
57
57
  Take a look at this [guide](https://express-rate-limit.mintlify.app/guides/creating-a-store) if you wish to create your own store.
58
58
 
59
+ ## Notes
60
+
61
+ - The `keyGenerator` function determines what to limit a request on, it should represent a unique characteristic of a user or class of user that you wish to rate limit. Good choices include API keys in `Authorization` headers, URL paths or routes, specific query parameters used by your application, and/or user IDs.
62
+ - It is not recommended to use IP addresses (since these can be shared by many users in many valid cases) or locations (the same), as you may find yourself unintentionally rate limiting a wider group of users than you intended.
63
+
59
64
  ## Contributing
60
65
 
61
66
  We would love to have more contributors involved!
package/index.cjs.js CHANGED
@@ -10,6 +10,6 @@ class MemoryStore{init(options){this.windowMs=options.windowMs;if(this.interval)
10
10
 
11
11
  const isValidStore=value=>!!value?.increment;
12
12
 
13
- function rateLimiter(config){const{windowMs=6e4,limit=5,message="Too many requests, please try again later.",statusCode=429,standardHeaders="draft-6",requestPropertyName="rateLimit",requestStorePropertyName="rateLimitStore",skipFailedRequests=false,skipSuccessfulRequests=false,keyGenerator=c=>c.req.header("cf-connecting-ip")??"",skip=()=>false,requestWasSuccessful=c=>c.res.status<400,handler=async(c,_next,options)=>{c.status(options.statusCode);const responseMessage=typeof options.message==="function"?await options.message(c):options.message;if(typeof responseMessage==="string")return c.text(responseMessage);return c.json(responseMessage)},store=new MemoryStore}=config??{};const options={windowMs,limit,message,statusCode,standardHeaders,requestPropertyName,requestStorePropertyName,skipFailedRequests,skipSuccessfulRequests,keyGenerator,skip,requestWasSuccessful,handler,store};if(!isValidStore(store))throw new Error("The store is not correctly implmented!");if(typeof store.init==="function")store.init(options);return factory.createMiddleware(async(c,next)=>{const isSkippable=await skip(c);if(isSkippable){await next();return}const key=await keyGenerator(c);const{totalHits,resetTime}=await store.increment(key);const retrieveLimit=typeof limit==="function"?limit(c):limit;const _limit=await retrieveLimit;const info={limit:_limit,used:totalHits,remaining:Math.max(_limit-totalHits,0),resetTime};c.set(requestPropertyName,info);c.set(requestStorePropertyName,{getKey:store.get?.bind(store),resetKey:store.resetKey.bind(store)});if(standardHeaders&&!c.finalized){if(standardHeaders==="draft-7"){setDraft7Headers(c,info,windowMs);}else {setDraft6Headers(c,info,windowMs);}}let decremented=false;const decrementKey=async()=>{if(!decremented){await store.decrement(key);decremented=true;}};const shouldSkipRequest=async()=>{if(skipFailedRequests||skipSuccessfulRequests){const wasRequestSuccessful=await requestWasSuccessful(c);if(skipFailedRequests&&!wasRequestSuccessful||skipSuccessfulRequests&&wasRequestSuccessful)await decrementKey();}};if(totalHits>_limit){if(standardHeaders){setRetryAfterHeader(c,info,windowMs);}await shouldSkipRequest();return handler(c,next,options)}try{await next();await shouldSkipRequest();}catch(error){if(skipFailedRequests)await decrementKey();}finally{if(!c.finalized)await decrementKey();}})}
13
+ function rateLimiter(config){const{windowMs=6e4,limit=5,message="Too many requests, please try again later.",statusCode=429,standardHeaders="draft-6",requestPropertyName="rateLimit",requestStorePropertyName="rateLimitStore",skipFailedRequests=false,skipSuccessfulRequests=false,keyGenerator,skip=()=>false,requestWasSuccessful=c=>c.res.status<400,handler=async(c,_next,options)=>{c.status(options.statusCode);const responseMessage=typeof options.message==="function"?await options.message(c):options.message;if(typeof responseMessage==="string")return c.text(responseMessage);return c.json(responseMessage)},store=new MemoryStore}=config??{};const options={windowMs,limit,message,statusCode,standardHeaders,requestPropertyName,requestStorePropertyName,skipFailedRequests,skipSuccessfulRequests,keyGenerator,skip,requestWasSuccessful,handler,store};if(!isValidStore(store))throw new Error("The store is not correctly implmented!");if(typeof store.init==="function")store.init(options);return factory.createMiddleware(async(c,next)=>{const isSkippable=await skip(c);if(isSkippable){await next();return}const key=await keyGenerator(c);const{totalHits,resetTime}=await store.increment(key);const retrieveLimit=typeof limit==="function"?limit(c):limit;const _limit=await retrieveLimit;const info={limit:_limit,used:totalHits,remaining:Math.max(_limit-totalHits,0),resetTime};c.set(requestPropertyName,info);c.set(requestStorePropertyName,{getKey:store.get?.bind(store),resetKey:store.resetKey.bind(store)});if(standardHeaders&&!c.finalized){if(standardHeaders==="draft-7"){setDraft7Headers(c,info,windowMs);}else {setDraft6Headers(c,info,windowMs);}}let decremented=false;const decrementKey=async()=>{if(!decremented){await store.decrement(key);decremented=true;}};const shouldSkipRequest=async()=>{if(skipFailedRequests||skipSuccessfulRequests){const wasRequestSuccessful=await requestWasSuccessful(c);if(skipFailedRequests&&!wasRequestSuccessful||skipSuccessfulRequests&&wasRequestSuccessful)await decrementKey();}};if(totalHits>_limit){if(standardHeaders){setRetryAfterHeader(c,info,windowMs);}await shouldSkipRequest();return handler(c,next,options)}try{await next();await shouldSkipRequest();}catch(error){if(skipFailedRequests)await decrementKey();}finally{if(!c.finalized)await decrementKey();}})}
14
14
 
15
15
  exports.rateLimiter = rateLimiter;
package/index.esm.js CHANGED
@@ -6,6 +6,6 @@ class MemoryStore{init(options){this.windowMs=options.windowMs;if(this.interval)
6
6
 
7
7
  const isValidStore=value=>!!value?.increment;
8
8
 
9
- function rateLimiter(config){const{windowMs=6e4,limit=5,message="Too many requests, please try again later.",statusCode=429,standardHeaders="draft-6",requestPropertyName="rateLimit",requestStorePropertyName="rateLimitStore",skipFailedRequests=false,skipSuccessfulRequests=false,keyGenerator=c=>c.req.header("cf-connecting-ip")??"",skip=()=>false,requestWasSuccessful=c=>c.res.status<400,handler=async(c,_next,options)=>{c.status(options.statusCode);const responseMessage=typeof options.message==="function"?await options.message(c):options.message;if(typeof responseMessage==="string")return c.text(responseMessage);return c.json(responseMessage)},store=new MemoryStore}=config??{};const options={windowMs,limit,message,statusCode,standardHeaders,requestPropertyName,requestStorePropertyName,skipFailedRequests,skipSuccessfulRequests,keyGenerator,skip,requestWasSuccessful,handler,store};if(!isValidStore(store))throw new Error("The store is not correctly implmented!");if(typeof store.init==="function")store.init(options);return createMiddleware(async(c,next)=>{const isSkippable=await skip(c);if(isSkippable){await next();return}const key=await keyGenerator(c);const{totalHits,resetTime}=await store.increment(key);const retrieveLimit=typeof limit==="function"?limit(c):limit;const _limit=await retrieveLimit;const info={limit:_limit,used:totalHits,remaining:Math.max(_limit-totalHits,0),resetTime};c.set(requestPropertyName,info);c.set(requestStorePropertyName,{getKey:store.get?.bind(store),resetKey:store.resetKey.bind(store)});if(standardHeaders&&!c.finalized){if(standardHeaders==="draft-7"){setDraft7Headers(c,info,windowMs);}else {setDraft6Headers(c,info,windowMs);}}let decremented=false;const decrementKey=async()=>{if(!decremented){await store.decrement(key);decremented=true;}};const shouldSkipRequest=async()=>{if(skipFailedRequests||skipSuccessfulRequests){const wasRequestSuccessful=await requestWasSuccessful(c);if(skipFailedRequests&&!wasRequestSuccessful||skipSuccessfulRequests&&wasRequestSuccessful)await decrementKey();}};if(totalHits>_limit){if(standardHeaders){setRetryAfterHeader(c,info,windowMs);}await shouldSkipRequest();return handler(c,next,options)}try{await next();await shouldSkipRequest();}catch(error){if(skipFailedRequests)await decrementKey();}finally{if(!c.finalized)await decrementKey();}})}
9
+ function rateLimiter(config){const{windowMs=6e4,limit=5,message="Too many requests, please try again later.",statusCode=429,standardHeaders="draft-6",requestPropertyName="rateLimit",requestStorePropertyName="rateLimitStore",skipFailedRequests=false,skipSuccessfulRequests=false,keyGenerator,skip=()=>false,requestWasSuccessful=c=>c.res.status<400,handler=async(c,_next,options)=>{c.status(options.statusCode);const responseMessage=typeof options.message==="function"?await options.message(c):options.message;if(typeof responseMessage==="string")return c.text(responseMessage);return c.json(responseMessage)},store=new MemoryStore}=config??{};const options={windowMs,limit,message,statusCode,standardHeaders,requestPropertyName,requestStorePropertyName,skipFailedRequests,skipSuccessfulRequests,keyGenerator,skip,requestWasSuccessful,handler,store};if(!isValidStore(store))throw new Error("The store is not correctly implmented!");if(typeof store.init==="function")store.init(options);return createMiddleware(async(c,next)=>{const isSkippable=await skip(c);if(isSkippable){await next();return}const key=await keyGenerator(c);const{totalHits,resetTime}=await store.increment(key);const retrieveLimit=typeof limit==="function"?limit(c):limit;const _limit=await retrieveLimit;const info={limit:_limit,used:totalHits,remaining:Math.max(_limit-totalHits,0),resetTime};c.set(requestPropertyName,info);c.set(requestStorePropertyName,{getKey:store.get?.bind(store),resetKey:store.resetKey.bind(store)});if(standardHeaders&&!c.finalized){if(standardHeaders==="draft-7"){setDraft7Headers(c,info,windowMs);}else {setDraft6Headers(c,info,windowMs);}}let decremented=false;const decrementKey=async()=>{if(!decremented){await store.decrement(key);decremented=true;}};const shouldSkipRequest=async()=>{if(skipFailedRequests||skipSuccessfulRequests){const wasRequestSuccessful=await requestWasSuccessful(c);if(skipFailedRequests&&!wasRequestSuccessful||skipSuccessfulRequests&&wasRequestSuccessful)await decrementKey();}};if(totalHits>_limit){if(standardHeaders){setRetryAfterHeader(c,info,windowMs);}await shouldSkipRequest();return handler(c,next,options)}try{await next();await shouldSkipRequest();}catch(error){if(skipFailedRequests)await decrementKey();}finally{if(!c.finalized)await decrementKey();}})}
10
10
 
11
11
  export { rateLimiter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-rate-limiter",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "keywords": [
6
6
  "hono",
package/src/core.d.ts CHANGED
@@ -10,4 +10,4 @@ import type { ConfigType } from "./types";
10
10
  *
11
11
  * @public
12
12
  */
13
- export declare function rateLimiter<E extends Env = Env, P extends string = string, I extends Input = Input>(config?: Partial<ConfigType<E, P, I>>): import("hono").MiddlewareHandler<E, P, I>;
13
+ export declare function rateLimiter<E extends Env = Env, P extends string = string, I extends Input = Input>(config: Pick<ConfigType<E, P, I>, "keyGenerator"> & Partial<Omit<ConfigType<E, P, I>, "keyGenerator">>): import("hono").MiddlewareHandler<E, P, I>;
package/src/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export { rateLimiter } from "./core";
2
- export * from "./types";
2
+ export type * from "./types";
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" />
2
+ import type { Env, Input } from "hono/types";
2
3
  import type { ClientRateLimitInfo, ConfigType, Store } from "./types";
3
4
  /**
4
5
  * The record that stores information about a client - namely, how many times
@@ -15,7 +16,7 @@ type Client = {
15
16
  *
16
17
  * @public
17
18
  */
18
- export declare class MemoryStore implements Store {
19
+ export declare class MemoryStore<E extends Env = Env, P extends string = string, I extends Input = Input> implements Store<E, P, I> {
19
20
  /**
20
21
  * The duration of time before which all hit counts are reset (in milliseconds).
21
22
  */
@@ -46,7 +47,7 @@ export declare class MemoryStore implements Store {
46
47
  *
47
48
  * @param options {ConfigType} - The options used to setup the middleware.
48
49
  */
49
- init(options: ConfigType): void;
50
+ init(options: ConfigType<E, P, I>): void;
50
51
  /**
51
52
  * Method to fetch a client's hit count and reset time.
52
53
  *
package/src/types.d.ts CHANGED
@@ -36,11 +36,11 @@ export type RateLimitInfo = {
36
36
  * @param next {Next} - The Hono `next` function, can be called to skip responding.
37
37
  * @param optionsUsed {ConfigType} - The options used to set up the middleware.
38
38
  */
39
- export type RateLimitExceededEventHandler<E extends Env = any, P extends string = any, I extends Input = NonNullable<unknown>> = (c: Context<E, P, I>, next: Next, optionsUsed: ConfigType<E, P, I>) => void;
39
+ export type RateLimitExceededEventHandler<E extends Env = Env, P extends string = string, I extends Input = Input> = (c: Context<E, P, I>, next: Next, optionsUsed: ConfigType<E, P, I>) => void;
40
40
  /**
41
41
  * The configuration options for the rate limiter.
42
42
  */
43
- export type ConfigType<E extends Env = any, P extends string = any, I extends Input = NonNullable<unknown>> = {
43
+ export type ConfigType<E extends Env = Env, P extends string = string, I extends Input = Input> = {
44
44
  /**
45
45
  * How long we should remember the requests.
46
46
  *
@@ -134,20 +134,20 @@ export type ConfigType<E extends Env = any, P extends string = any, I extends In
134
134
  *
135
135
  * By default, the built-in `MemoryStore` will be used.
136
136
  */
137
- store: Store;
137
+ store: Store<E, P, I>;
138
138
  };
139
139
  export type IncrementResponse = ClientRateLimitInfo;
140
140
  /**
141
141
  * An interface that all hit counter stores must implement.
142
142
  */
143
- export type Store = {
143
+ export type Store<E extends Env = Env, P extends string = string, I extends Input = Input> = {
144
144
  /**
145
145
  * Method that initializes the store, and has access to the options passed to
146
146
  * the middleware too.
147
147
  *
148
148
  * @param options {ConfigType} - The options used to setup the middleware.
149
149
  */
150
- init?: (options: ConfigType) => void;
150
+ init?: (options: ConfigType<E, P, I>) => void;
151
151
  /**
152
152
  * Method to fetch a client's hit count and reset time.
153
153
  *
@@ -1,2 +1,3 @@
1
+ import type { Env, Input } from "hono/types";
1
2
  import type { Store } from "./types";
2
- export declare const isValidStore: (value: Store) => value is Store;
3
+ export declare const isValidStore: <E extends Env = Env, P extends string = string, I extends Input = Input>(value: Store<E, P, I>) => value is Store<E, P, I>;