hono-rate-limiter 0.2.3 → 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
@@ -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
 
@@ -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. |
@@ -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,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=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 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=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 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.2.3",
3
+ "version": "0.4.0-rc.0",
4
4
  "license": "MIT",
5
5
  "keywords": [
6
6
  "hono",
package/src/core.d.ts CHANGED
@@ -2,12 +2,12 @@ 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
  *
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,3 @@
1
1
  export { rateLimiter } from "./core";
2
- export * from "./types";
2
+ export { webSocketLimiter } from "./websocket";
3
+ export type * from "./types";
@@ -1,5 +1,6 @@
1
1
  /// <reference types="node" />
2
- import type { ClientRateLimitInfo, ConfigType, Store } from "./types";
2
+ import type { Env, Input } from "hono/types";
3
+ import type { ClientRateLimitInfo, ConfigType, Store, WSConfigType } from "./types";
3
4
  /**
4
5
  * The record that stores information about a client - namely, how many times
5
6
  * they have hit the endpoint, and when their hit count resets.
@@ -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> | WSConfigType<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
@@ -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
  *
@@ -36,11 +37,11 @@ export type RateLimitInfo = {
36
37
  * @param next {Next} - The Hono `next` function, can be called to skip responding.
37
38
  * @param optionsUsed {ConfigType} - The options used to set up the middleware.
38
39
  */
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;
40
+ 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
41
  /**
41
42
  * The configuration options for the rate limiter.
42
43
  */
43
- export type ConfigType<E extends Env = any, P extends string = any, I extends Input = NonNullable<unknown>> = {
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 = any, P extends string = any, I extends In
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
  /**
@@ -134,20 +133,61 @@ export type ConfigType<E extends Env = any, P extends string = any, I extends In
134
133
  *
135
134
  * By default, the built-in `MemoryStore` will be used.
136
135
  */
137
- store: Store;
138
- };
136
+ store: Store<E, P, I>;
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.
142
182
  */
143
- export type Store = {
183
+ export type Store<E extends Env = Env, P extends string = string, I extends Input = Input> = {
144
184
  /**
145
185
  * Method that initializes the store, and has access to the options passed to
146
186
  * the middleware too.
147
187
  *
148
188
  * @param options {ConfigType} - The options used to setup the middleware.
149
189
  */
150
- init?: (options: ConfigType) => void;
190
+ init?: (options: ConfigType<E, P, I>) => void;
151
191
  /**
152
192
  * Method to fetch a client's hit count and reset time.
153
193
  *
@@ -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>;
@@ -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>>;