hono-rate-limiter 0.2.1 → 0.2.3

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
@@ -24,7 +24,7 @@ const limiter = rateLimiter({
24
24
  windowMs: 15 * 60 * 1000, // 15 minutes
25
25
  limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
26
26
  standardHeaders: "draft-6", // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header
27
- keyGenerator: () => "<unique_key>", // Method to generate custom identifiers for clients.
27
+ keyGenerator: (c) => "<unique_key>", // Method to generate custom identifiers for clients.
28
28
  // store: ... , // Redis, MemoryStore, etc. See below.
29
29
  });
30
30
 
@@ -32,7 +32,7 @@ const limiter = rateLimiter({
32
32
  app.use(limiter);
33
33
  ```
34
34
 
35
- # Data Stores
35
+ ## Data Stores
36
36
 
37
37
  `hono-rate-limit` supports external data stores to synchronize hit counts across multiple processes and servers.
38
38
 
@@ -45,6 +45,7 @@ Here is a list of stores:
45
45
  | Name | Description |
46
46
  | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
47
47
  | MemoryStore | (default) Simple in-memory option. Does not share state when the app has multiple processes or servers. |
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) |
48
49
  | [`rate-limit-redis`](https://npm.im/rate-limit-redis) | A [Redis](https://redis.io/)-backed store, more suitable for large or demanding deployments. |
49
50
  | [`rate-limit-postresql`](https://www.npm.im/@acpr/rate-limit-postgresql) | A [PostgreSQL](https://www.postgresql.org/)-backed store. |
50
51
  | [`rate-limit-memecached`](https://npmjs.org/package/rate-limit-memcached) | A [Memcached](https://memcached.org/)-backed store. |
@@ -55,12 +56,12 @@ Here is a list of stores:
55
56
 
56
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.
57
58
 
58
- # Contributing
59
+ ## Contributing
59
60
 
60
61
  We would love to have more contributors involved!
61
62
 
62
63
  To get started, please read our [Contributing Guide](https://github.com/rhinobase/hono-rate-limiter/blob/main/CONTRIBUTING.md).
63
64
 
64
- # Credits
65
+ ## Credits
65
66
 
66
67
  The `hono-rate-limiter` project is heavily inspired by [express-rate-limit](https://github.com/express-rate-limit/express-rate-limit)
package/index.cjs.js CHANGED
@@ -3,9 +3,6 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var factory = require('hono/factory');
6
- var adapter = require('hono/adapter');
7
-
8
- function defaultKeyGenerator(c){const runtime=adapter.getRuntimeKey();let key=null;switch(runtime){case"workerd":key=c.req.raw.headers.get("CF-Connecting-IP");break;case"fastly":key=c.req.raw.headers.get("Fastly-Client-IP");break;case"other":key=c.req.raw.headers.get("x-real-ip");break;}return key??""}
9
6
 
10
7
  const getResetSeconds=(resetTime,windowMs)=>{let resetSeconds;if(resetTime){const deltaSeconds=Math.ceil((resetTime.getTime()-Date.now())/1e3);resetSeconds=Math.max(0,deltaSeconds);}else if(windowMs){resetSeconds=Math.ceil(windowMs/1e3);}return resetSeconds};const setDraft6Headers=(context,info,windowMs)=>{if(context.finalized)return;const windowSeconds=Math.ceil(windowMs/1e3);const resetSeconds=getResetSeconds(info.resetTime);context.header("RateLimit-Policy",`${info.limit};w=${windowSeconds}`);context.header("RateLimit-Limit",info.limit.toString());context.header("RateLimit-Remaining",info.remaining.toString());if(resetSeconds)context.header("RateLimit-Reset",resetSeconds.toString());};const setDraft7Headers=(context,info,windowMs)=>{if(context.finalized)return;const windowSeconds=Math.ceil(windowMs/1e3);const resetSeconds=getResetSeconds(info.resetTime,windowMs);context.header("RateLimit-Policy",`${info.limit};w=${windowSeconds}`);context.header("RateLimit",`limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`);};const setRetryAfterHeader=(context,info,windowMs)=>{if(context.finalized)return;const resetSeconds=getResetSeconds(info.resetTime,windowMs);context.header("Retry-After",resetSeconds?.toString());};
11
8
 
@@ -13,6 +10,6 @@ class MemoryStore{init(options){this.windowMs=options.windowMs;if(this.interval)
13
10
 
14
11
  const isValidStore=value=>!!value?.increment;
15
12
 
16
- 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=defaultKeyGenerator,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=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();}})}
17
14
 
18
15
  exports.rateLimiter = rateLimiter;
package/index.esm.js CHANGED
@@ -1,7 +1,4 @@
1
1
  import { createMiddleware } from 'hono/factory';
2
- import { getRuntimeKey } from 'hono/adapter';
3
-
4
- function defaultKeyGenerator(c){const runtime=getRuntimeKey();let key=null;switch(runtime){case"workerd":key=c.req.raw.headers.get("CF-Connecting-IP");break;case"fastly":key=c.req.raw.headers.get("Fastly-Client-IP");break;case"other":key=c.req.raw.headers.get("x-real-ip");break;}return key??""}
5
2
 
6
3
  const getResetSeconds=(resetTime,windowMs)=>{let resetSeconds;if(resetTime){const deltaSeconds=Math.ceil((resetTime.getTime()-Date.now())/1e3);resetSeconds=Math.max(0,deltaSeconds);}else if(windowMs){resetSeconds=Math.ceil(windowMs/1e3);}return resetSeconds};const setDraft6Headers=(context,info,windowMs)=>{if(context.finalized)return;const windowSeconds=Math.ceil(windowMs/1e3);const resetSeconds=getResetSeconds(info.resetTime);context.header("RateLimit-Policy",`${info.limit};w=${windowSeconds}`);context.header("RateLimit-Limit",info.limit.toString());context.header("RateLimit-Remaining",info.remaining.toString());if(resetSeconds)context.header("RateLimit-Reset",resetSeconds.toString());};const setDraft7Headers=(context,info,windowMs)=>{if(context.finalized)return;const windowSeconds=Math.ceil(windowMs/1e3);const resetSeconds=getResetSeconds(info.resetTime,windowMs);context.header("RateLimit-Policy",`${info.limit};w=${windowSeconds}`);context.header("RateLimit",`limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`);};const setRetryAfterHeader=(context,info,windowMs)=>{if(context.finalized)return;const resetSeconds=getResetSeconds(info.resetTime,windowMs);context.header("Retry-After",resetSeconds?.toString());};
7
4
 
@@ -9,6 +6,6 @@ class MemoryStore{init(options){this.windowMs=options.windowMs;if(this.interval)
9
6
 
10
7
  const isValidStore=value=>!!value?.increment;
11
8
 
12
- 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=defaultKeyGenerator,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=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();}})}
13
10
 
14
11
  export { rateLimiter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-rate-limiter",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "license": "MIT",
5
5
  "keywords": [
6
6
  "hono",
@@ -11,14 +11,14 @@
11
11
  "rate-limiter",
12
12
  "honojs"
13
13
  ],
14
- "homepage": "https://github.com/rhinobase/hono-rate-limiter",
14
+ "homepage": "https://hono-rate-limiter.vercel.app",
15
15
  "publishConfig": {
16
16
  "access": "public"
17
17
  },
18
18
  "repository": {
19
19
  "type": "git",
20
20
  "url": "git+https://github.com/rhinobase/hono-rate-limiter.git",
21
- "directory": "packages/ui"
21
+ "directory": "packages/core"
22
22
  },
23
23
  "bugs": {
24
24
  "url": "https://github.com/rhinobase/hono-rate-limiter/issues"
package/src/types.d.ts CHANGED
@@ -10,6 +10,13 @@ export type ClientRateLimitInfo = {
10
10
  totalHits: number;
11
11
  resetTime?: Date;
12
12
  };
13
+ /**
14
+ * Promisify<T> is a utility type that represents a value of type T or a Promise<T>.
15
+ * This type is useful for converting synchronous functions to asynchronous functions.
16
+ * @example
17
+ * type getResult = Promisify<number>; // getResult can be number or Promise<number>
18
+ * type getUser = Promisify<User>; // getUser can be User or Promise<User>
19
+ */
13
20
  export type Promisify<T> = T | Promise<T>;
14
21
  /**
15
22
  * The rate limit related information for each client included in the
@@ -148,7 +155,7 @@ export type Store = {
148
155
  *
149
156
  * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client.
150
157
  */
151
- get?: (key: string) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;
158
+ get?: (key: string) => Promisify<ClientRateLimitInfo | undefined>;
152
159
  /**
153
160
  * Method to increment a client's hit counter.
154
161
  *
@@ -156,27 +163,27 @@ export type Store = {
156
163
  *
157
164
  * @returns {IncrementResponse | undefined} - The number of hits and reset time for that client.
158
165
  */
159
- increment: (key: string) => Promise<IncrementResponse> | IncrementResponse;
166
+ increment: (key: string) => Promisify<IncrementResponse>;
160
167
  /**
161
168
  * Method to decrement a client's hit counter.
162
169
  *
163
170
  * @param key {string} - The identifier for a client.
164
171
  */
165
- decrement: (key: string) => Promise<void> | void;
172
+ decrement: (key: string) => Promisify<void>;
166
173
  /**
167
174
  * Method to reset a client's hit counter.
168
175
  *
169
176
  * @param key {string} - The identifier for a client.
170
177
  */
171
- resetKey: (key: string) => Promise<void> | void;
178
+ resetKey: (key: string) => Promisify<void>;
172
179
  /**
173
180
  * Method to reset everyone's hit counter.
174
181
  */
175
- resetAll?: () => Promise<void> | void;
182
+ resetAll?: () => Promisify<void>;
176
183
  /**
177
184
  * Method to shutdown the store, stop timers, and release all resources.
178
185
  */
179
- shutdown?: () => Promise<void> | void;
186
+ shutdown?: () => Promisify<void>;
180
187
  /**
181
188
  * Flag to indicate that keys incremented in one instance of this store can
182
189
  * not affect other instances. Typically false if a database is used, true for
@@ -1,2 +0,0 @@
1
- import type { Context, Env, Input } from "hono";
2
- export declare function defaultKeyGenerator<E extends Env, P extends string, I extends Input>(c: Context<E, P, I>): string;