hono-rate-limiter 0.3.0 → 0.4.0-rc.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
@@ -47,8 +47,8 @@ Here is a list of stores:
47
47
  | MemoryStore | (default) Simple in-memory option. Does not share state when the app has multiple processes or servers. |
48
48
  | [`@hono-rate-limiter/redis`](https://www.npm.im/@hono-rate-limiter/redis) | A [Redis](https://redis.io/)-backed store, used with [`@vercel/kv`](https://www.npmjs.com/package/@vercel/kv) and [`@upstash/redis`](https://www.npmjs.com/package/@upstash/redis) |
49
49
  | [`rate-limit-redis`](https://npm.im/rate-limit-redis) | A [Redis](https://redis.io/)-backed store, more suitable for large or demanding deployments. |
50
- | [`rate-limit-postresql`](https://www.npm.im/@acpr/rate-limit-postgresql) | A [PostgreSQL](https://www.postgresql.org/)-backed store. |
51
- | [`rate-limit-memecached`](https://npmjs.org/package/rate-limit-memcached) | A [Memcached](https://memcached.org/)-backed store. |
50
+ | [`rate-limit-postgresql`](https://www.npm.im/@acpr/rate-limit-postgresql) | A [PostgreSQL](https://www.postgresql.org/)-backed store. |
51
+ | [`rate-limit-memcached`](https://npmjs.org/package/rate-limit-memcached) | A [Memcached](https://memcached.org/)-backed store. |
52
52
  | [`cluster-memory-store`](https://npm.im/@express-rate-limit/cluster-memory-store) | A memory-store wrapper that shares state across all processes on a single server via the [node:cluster](https://nodejs.org/api/cluster.html) module. Does not share state across multiple servers. |
53
53
  | [`precise-memory-rate-limit`](https://www.npm.im/precise-memory-rate-limit) | A memory store similar to the built-in one, except that it stores a distinct timestamp for each key. |
54
54
  | [`typeorm-rate-limit-store`](https://www.npmjs.com/package/typeorm-rate-limit-store) | Supports a variety of databases via [TypeORM](https://typeorm.io/): MySQL, MariaDB, CockroachDB, SQLite, Microsoft SQL Server, Oracle, SAP Hana, and more. |
package/index.cjs.js CHANGED
@@ -10,6 +10,9 @@ 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,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 implemented!");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
+
15
+ async function webSocketLimiter(config){const{windowMs=6e4,limit=5,message="Too many requests, please try again later.",statusCode=1008,requestPropertyName="rateLimit",requestStorePropertyName="rateLimitStore",skipFailedRequests=false,skipSuccessfulRequests=false,keyGenerator,skip=()=>false,handler=async(_,ws,options)=>ws.close(options.statusCode,options.message),store=new MemoryStore}=config??{};const options={windowMs,limit,message,statusCode,requestPropertyName,requestStorePropertyName,skipFailedRequests,skipSuccessfulRequests,keyGenerator,skip,handler,store};if(!isValidStore(store))throw new Error("The store is not correctly implemented!");if(typeof store.init==="function")store.init(options);return createEvents=>{return async c=>{const events=await createEvents(c);return {...events,onMessage:async(event,ws)=>{const isSkippable=await skip(event,ws);if(isSkippable){await events.onMessage?.(event,ws);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)});let decremented=false;const decrementKey=async()=>{if(!decremented){await store.decrement(key);decremented=true;}};const shouldSkipRequest=async()=>{if(skipSuccessfulRequests)await decrementKey();};if(totalHits>_limit){await shouldSkipRequest();return handler(event,ws,options)}try{await events.onMessage?.(event,ws);await shouldSkipRequest();}catch(error){if(skipFailedRequests)await decrementKey();}finally{if(!c.finalized)await decrementKey();}},onError:async(event,ws)=>{if(skipFailedRequests){const key=await keyGenerator(c);await store.decrement(key);}events.onError?.(event,ws);}}}}}
14
16
 
15
17
  exports.rateLimiter = rateLimiter;
18
+ exports.webSocketLimiter = webSocketLimiter;
package/index.esm.js CHANGED
@@ -6,6 +6,8 @@ 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,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 implemented!");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
- export { rateLimiter };
11
+ async function webSocketLimiter(config){const{windowMs=6e4,limit=5,message="Too many requests, please try again later.",statusCode=1008,requestPropertyName="rateLimit",requestStorePropertyName="rateLimitStore",skipFailedRequests=false,skipSuccessfulRequests=false,keyGenerator,skip=()=>false,handler=async(_,ws,options)=>ws.close(options.statusCode,options.message),store=new MemoryStore}=config??{};const options={windowMs,limit,message,statusCode,requestPropertyName,requestStorePropertyName,skipFailedRequests,skipSuccessfulRequests,keyGenerator,skip,handler,store};if(!isValidStore(store))throw new Error("The store is not correctly implemented!");if(typeof store.init==="function")store.init(options);return createEvents=>{return async c=>{const events=await createEvents(c);return {...events,onMessage:async(event,ws)=>{const isSkippable=await skip(event,ws);if(isSkippable){await events.onMessage?.(event,ws);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)});let decremented=false;const decrementKey=async()=>{if(!decremented){await store.decrement(key);decremented=true;}};const shouldSkipRequest=async()=>{if(skipSuccessfulRequests)await decrementKey();};if(totalHits>_limit){await shouldSkipRequest();return handler(event,ws,options)}try{await events.onMessage?.(event,ws);await shouldSkipRequest();}catch(error){if(skipFailedRequests)await decrementKey();}finally{if(!c.finalized)await decrementKey();}},onError:async(event,ws)=>{if(skipFailedRequests){const key=await keyGenerator(c);await store.decrement(key);}events.onError?.(event,ws);}}}}}
12
+
13
+ export { rateLimiter, webSocketLimiter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-rate-limiter",
3
- "version": "0.3.0",
3
+ "version": "0.4.0-rc.0",
4
4
  "license": "MIT",
5
5
  "keywords": [
6
6
  "hono",
package/src/core.d.ts CHANGED
@@ -2,9 +2,9 @@ import type { Env, Input } from "hono";
2
2
  import type { ConfigType } from "./types";
3
3
  /**
4
4
  *
5
- * Create an instance of IP rate-limiting middleware for Hono.
5
+ * Create an instance of rate-limiting middleware for Hono.
6
6
  *
7
- * @param config {ConfigType} - Options to configure the rate limiter.
7
+ * @param config x{ConfigType} - Options to configure the rate limiter.
8
8
  *
9
9
  * @returns - The middleware that rate-limits clients based on your configuration.
10
10
  *
package/src/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export { rateLimiter } from "./core";
2
+ export { webSocketLimiter } from "./websocket";
2
3
  export type * from "./types";
package/src/store.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  import type { Env, Input } from "hono/types";
3
- import type { ClientRateLimitInfo, ConfigType, Store } from "./types";
3
+ import type { ClientRateLimitInfo, ConfigType, Store, WSConfigType } from "./types";
4
4
  /**
5
5
  * The record that stores information about a client - namely, how many times
6
6
  * they have hit the endpoint, and when their hit count resets.
@@ -47,7 +47,7 @@ export declare class MemoryStore<E extends Env = Env, P extends string = string,
47
47
  *
48
48
  * @param options {ConfigType} - The options used to setup the middleware.
49
49
  */
50
- init(options: ConfigType<E, P, I>): void;
50
+ init(options: ConfigType<E, P, I> | WSConfigType<E, P, I>): void;
51
51
  /**
52
52
  * Method to fetch a client's hit count and reset time.
53
53
  *
package/src/types.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Context, Env, Input, Next } from "hono";
2
2
  import type { StatusCode } from "hono/utils/http-status";
3
+ import type { WSContext } from "hono/ws";
3
4
  /**
4
5
  * Data returned from the `Store` when a client's hit counter is incremented.
5
6
  *
@@ -40,7 +41,7 @@ export type RateLimitExceededEventHandler<E extends Env = Env, P extends string
40
41
  /**
41
42
  * The configuration options for the rate limiter.
42
43
  */
43
- export type ConfigType<E extends Env = Env, P extends string = string, I extends Input = Input> = {
44
+ export interface ConfigType<E extends Env = Env, P extends string = string, I extends Input = Input> {
44
45
  /**
45
46
  * How long we should remember the requests.
46
47
  *
@@ -103,8 +104,6 @@ export type ConfigType<E extends Env = Env, P extends string = string, I extends
103
104
  skipSuccessfulRequests: boolean;
104
105
  /**
105
106
  * Method to generate custom identifiers for clients.
106
- *
107
- * By default, the client's IP address is used.
108
107
  */
109
108
  keyGenerator: (c: Context<E, P, I>) => Promisify<string>;
110
109
  /**
@@ -135,7 +134,48 @@ export type ConfigType<E extends Env = Env, P extends string = string, I extends
135
134
  * By default, the built-in `MemoryStore` will be used.
136
135
  */
137
136
  store: Store<E, P, I>;
138
- };
137
+ }
138
+ export type WSStatusCode = 1000 | 1001 | 1002 | 1003 | 1004 | 1005 | 1006 | 1007 | 1008 | 1009 | 1010;
139
+ /**
140
+ * Hono request handler that sends back a response when a client is
141
+ * rate-limited.
142
+ *
143
+ * @param context {Context} - The Hono context object.
144
+ * @param next {Next} - The Hono `next` function, can be called to skip responding.
145
+ * @param optionsUsed {ConfigType} - The options used to set up the middleware.
146
+ */
147
+ export type WSRateLimitExceededEventHandler<E extends Env = Env, P extends string = string, I extends Input = Input> = (event: unknown, ws: WSContext, optionsUsed: WSConfigType<E, P, I>) => void;
148
+ /**
149
+ * The configuration options for the rate limiter.
150
+ */
151
+ export interface WSConfigType<E extends Env = Env, P extends string = string, I extends Input = Input> extends Omit<ConfigType<E, P, I>, "statusCode" | "standardHeaders" | "requestWasSuccessful" | "handler" | "skip"> {
152
+ /**
153
+ * The response body to send back when a client is rate limited.
154
+ *
155
+ * Defaults to `'Too many requests, please try again later.'`
156
+ */
157
+ message: string;
158
+ /**
159
+ * The ws status code to send back when a client is rate limited.
160
+ *
161
+ * Defaults to `HTTP 1008 Terminating The Connection` (RFC 6455).
162
+ */
163
+ statusCode: WSStatusCode;
164
+ /**
165
+ * Hono ws request handler that sends back a response when a client is
166
+ * rate-limited.
167
+ *
168
+ * By default, sends back the `statusCode` and `message` set via the options.
169
+ */
170
+ handler: WSRateLimitExceededEventHandler<E, P, I>;
171
+ /**
172
+ * Method (in the form of middleware) to determine whether or not this ws request
173
+ * counts towards a client's quota.
174
+ *
175
+ * By default, skips no requests.
176
+ */
177
+ skip: (event: unknown, ws: WSContext) => Promisify<boolean>;
178
+ }
139
179
  export type IncrementResponse = ClientRateLimitInfo;
140
180
  /**
141
181
  * An interface that all hit counter stores must implement.
@@ -0,0 +1,14 @@
1
+ import type { Context, Env, Input } from "hono";
2
+ import type { WSEvents } from "hono/ws";
3
+ import type { WSConfigType } from "./types";
4
+ /**
5
+ *
6
+ * Create an instance of ws based rate-limiting middleware for Hono.
7
+ *
8
+ * @param config {WSConfigType} - Options to configure the rate limiter.
9
+ *
10
+ * @returns - The middleware that rate-limits clients based on your configuration.
11
+ *
12
+ * @public
13
+ */
14
+ export declare function webSocketLimiter<E extends Env = Env, P extends string = string, I extends Input = Input>(config: Pick<WSConfigType<E, P, I>, "keyGenerator"> & Partial<Omit<WSConfigType<E, P, I>, "keyGenerator">>): Promise<(createEvents: (c: Context<E, P, I>) => WSEvents | Promise<WSEvents>) => (c: Context<E, P, I>) => Promise<WSEvents>>;