hono-rate-limiter 0.4.0 → 0.4.1

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
@@ -1,119 +1,155 @@
1
- <h1 align="center"> <code>🔥hono-rate-limiter🔥</code> </h1>
2
-
3
- <div align="center">
4
-
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
- [![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
- [![npm downloads](https://img.shields.io/npm/dm/hono-rate-limiter)](https://www.npmjs.com/package/hono-rate-limiter)
8
- [![license](https://img.shields.io/npm/l/hono-rate-limiter)](LICENSE)
9
-
10
- </div>
11
-
12
- Rate limiting middleware for [Hono](https://hono.dev/). Use to
13
- limit repeated requests to public APIs and/or endpoints such as password reset.
14
-
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
-
18
- ## Installation
19
-
20
- ```sh
21
- # Using npm/yarn/pnpm/bun
22
- npm add hono-rate-limiter
23
- ```
24
-
25
- ## Usage
26
-
27
- ### Rest APIs
28
-
29
- ```ts
30
- import { rateLimiter } from "hono-rate-limiter";
31
-
32
- const limiter = rateLimiter({
33
- windowMs: 15 * 60 * 1000, // 15 minutes
34
- limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
35
- standardHeaders: "draft-6", // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header
36
- keyGenerator: (c) => "<unique_key>", // Method to generate custom identifiers for clients.
37
- // store: ... , // Redis, MemoryStore, etc. See below.
38
- });
39
-
40
- // Apply the rate limiting middleware to all requests.
41
- app.use(limiter);
42
- ```
43
-
44
- ### WebSocket APIs
45
-
46
- ```ts
47
- import { webSocketLimiter } from "hono-rate-limiter";
48
- import { upgradeWebSocket } from "hono/cloudflare-workers";
49
- import { RedisStore } from "@hono-rate-limiter/redis";
50
- import { Redis } from "@upstash/redis/cloudflare";
51
-
52
- const limiter = webSocketLimiter({
53
- windowMs: 15 * 60 * 1000, // 15 minutes
54
- limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
55
- keyGenerator: (c) => "<unique_key>", // Method to generate custom identifiers for clients.
56
- store: new RedisStore({ client }), // Define your DataStore. See below.
57
- });
58
-
59
- // Apply the rate limiting middleware to ws requests.
60
- app.get(
61
- "/",
62
- upgradeWebSocket(
63
- limiter((c) => {
64
- return {
65
- onOpen: () => {
66
- console.log("Connection opened");
67
- },
68
- async onMessage(event, ws) {
69
- console.log(`Message from client: ${event.data}`);
70
- ws.send("Hello from server!");
71
- },
72
- onClose: () => {
73
- console.log("Connection closed");
74
- },
75
- };
76
- })
77
- )
78
- );
79
- ```
80
-
81
- ## Data Stores
82
-
83
- `hono-rate-limiter` supports external data stores to synchronize hit counts across multiple processes and servers.
84
-
85
- By default, `MemoryStore` is used. This one does not synchronize its state across instances. It’s simple to deploy, and often sufficient for basic abuse prevention, but will be inconnsistent across reboots or in deployments with multiple process or servers.
86
-
87
- Deployments requiring more consistently enforced rate limits should use an external store.
88
-
89
- Here is a list of stores:
90
-
91
- | Name | Description |
92
- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
93
- | MemoryStore | (default) Simple in-memory option. Does not share state when the app has multiple processes or servers. |
94
- | [`@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) |
95
- | [`@hono-rate-limiter/cloudflare`](https://www.npm.im/@hono-rate-limiter/cloudflare) | A [Cloudflare](https://www.cloudflare.com/)-backed store, used with [`WorkersKV`](https://developers.cloudflare.com/kv/) and [Workers Rate Limiting](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/) API |
96
- | [`rate-limit-redis`](https://npm.im/rate-limit-redis) | A [Redis](https://redis.io/)-backed store, more suitable for large or demanding deployments. |
97
- | [`rate-limit-postgresql`](https://www.npm.im/@acpr/rate-limit-postgresql) | A [PostgreSQL](https://www.postgresql.org/)-backed store. |
98
- | [`rate-limit-memcached`](https://npmjs.org/package/rate-limit-memcached) | A [Memcached](https://memcached.org/)-backed store. |
99
- | [`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. |
100
- | [`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. |
101
- | [`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. |
102
- | [`@rlimit/storage`](https://www.npmjs.com/package/@rlimit/storage) | A distributed rlimit store, ideal for multi-regional deployments. |
103
-
104
- Take a look at this [guide](https://express-rate-limit.mintlify.app/guides/creating-a-store) if you wish to create your own store.
105
-
106
- ## Notes
107
-
108
- - 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.
109
- - 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.
110
-
111
- ## Contributing
112
-
113
- We would love to have more contributors involved!
114
-
115
- To get started, please read our [Contributing Guide](https://github.com/rhinobase/hono-rate-limiter/blob/main/CONTRIBUTING.md).
116
-
117
- ## Credits
118
-
119
- The `hono-rate-limiter` project is heavily inspired by [express-rate-limit](https://github.com/express-rate-limit/express-rate-limit)
1
+ <h1 align="center"> <code>🔥hono-rate-limiter🔥</code> </h1>
2
+
3
+ <div align="center">
4
+
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
+ [![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
+ [![npm downloads](https://img.shields.io/npm/dm/hono-rate-limiter)](https://www.npmjs.com/package/hono-rate-limiter)
8
+ [![license](https://img.shields.io/npm/l/hono-rate-limiter)](LICENSE)
9
+
10
+ </div>
11
+
12
+ Rate limiting middleware for [Hono](https://hono.dev/). Use to
13
+ limit repeated requests to public APIs and/or endpoints such as password reset.
14
+
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
+
18
+ ## Installation
19
+
20
+ ```sh
21
+ # Using npm/yarn/pnpm/bun
22
+ npm add hono-rate-limiter
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ### Rest APIs
28
+
29
+ ```ts
30
+ import { rateLimiter } from "hono-rate-limiter";
31
+
32
+ // Apply the rate limiting middleware to all requests.
33
+ app.use(
34
+ rateLimiter({
35
+ windowMs: 15 * 60 * 1000, // 15 minutes
36
+ limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
37
+ standardHeaders: "draft-6", // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header
38
+ keyGenerator: (c) => "<unique_key>", // Method to generate custom identifiers for clients.
39
+ // store: ... , // Redis, MemoryStore, etc. See below.
40
+ })
41
+ );
42
+ ```
43
+
44
+ ### WebSocket APIs
45
+
46
+ ```ts
47
+ import { webSocketLimiter } from "hono-rate-limiter";
48
+ import { upgradeWebSocket } from "hono/cloudflare-workers";
49
+ import { RedisStore } from "@hono-rate-limiter/redis";
50
+ import { Redis } from "@upstash/redis/cloudflare";
51
+
52
+ const limiter = webSocketLimiter({
53
+ windowMs: 15 * 60 * 1000, // 15 minutes
54
+ limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
55
+ keyGenerator: (c) => "<unique_key>", // Method to generate custom identifiers for clients.
56
+ store: new RedisStore({ client }), // Define your DataStore. See below.
57
+ });
58
+
59
+ // Apply the rate limiting middleware to ws requests.
60
+ app.get(
61
+ "/",
62
+ upgradeWebSocket(
63
+ limiter((c) => {
64
+ return {
65
+ onOpen: () => {
66
+ console.log("Connection opened");
67
+ },
68
+ async onMessage(event, ws) {
69
+ console.log(`Message from client: ${event.data}`);
70
+ ws.send("Hello from server!");
71
+ },
72
+ onClose: () => {
73
+ console.log("Connection closed");
74
+ },
75
+ };
76
+ })
77
+ )
78
+ );
79
+ ```
80
+
81
+ ## Data Stores
82
+
83
+ `hono-rate-limiter` supports external data stores to synchronize hit counts across multiple processes and servers.
84
+
85
+ By default, `MemoryStore` is used. This one does not synchronize its state across instances. It’s simple to deploy, and often sufficient for basic abuse prevention, but will be inconsistent across reboots or in deployments with multiple process or servers.
86
+
87
+ Deployments requiring more consistently enforced rate limits should use an external store.
88
+
89
+ Here is a list of stores:
90
+
91
+ | Name | Description |
92
+ | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
93
+ | MemoryStore | (default) Simple in-memory option. Does not share state when the app has multiple processes or servers. |
94
+ | [@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) . [![npm downloads](https://img.shields.io/npm/dm/@hono-rate-limiter/redis)](https://www.npmjs.com/package/@hono-rate-limiter/redis) |
95
+ | [@hono-rate-limiter/cloudflare](https://www.npm.im/@hono-rate-limiter/cloudflare) | A [Cloudflare](https://www.cloudflare.com/)-backed store, used with [Durable Object](https://developers.cloudflare.com/durable-objects/), [WorkersKV](https://developers.cloudflare.com/kv/) and [Workers Rate Limiting](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/) API. [![npm downloads](https://img.shields.io/npm/dm/@hono-rate-limiter/cloudflare)](https://www.npmjs.com/package/@hono-rate-limiter/cloudflare) |
96
+ | [rate-limit-redis](https://npm.im/rate-limit-redis) | A [Redis](https://redis.io/)-backed store, more suitable for large or demanding deployments. |
97
+ | [rate-limit-postgresql](https://www.npm.im/@acpr/rate-limit-postgresql) | A [PostgreSQL](https://www.postgresql.org/)-backed store. |
98
+ | [rate-limit-memcached](https://npmjs.org/package/rate-limit-memcached) | A [Memcached](https://memcached.org/)-backed store. |
99
+ | [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. |
100
+ | [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. |
101
+ | [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. |
102
+ | [@rlimit/storage](https://www.npmjs.com/package/@rlimit/storage) | A distributed rlimit store, ideal for multi-regional deployments. |
103
+
104
+ Take a look at this [guide](https://express-rate-limit.mintlify.app/guides/creating-a-store) if you wish to create your own store.
105
+
106
+ ## Notes
107
+
108
+ - 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.
109
+ - 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.
110
+
111
+ ## Examples
112
+
113
+ - [hono-rate-limiter.vercel.app](https://hono-rate-limiter.vercel.app) - Uses Vercel KV and deployed on Vercel
114
+ - [hono-rate-limiter.rhinobase.workers.dev](https://hono-rate-limiter.rhinobase.workers.dev) - Built using Cloudflare Workers
115
+
116
+ ## Troubleshooting
117
+
118
+ If the suggestions here don't work, please try posting questions on [GitHub Discussions](https://github.com/rhinobase/hono-rate-limiter/discussions) or in the #help channel of [Hono Discord](https://discord.gg/xUtamz2vxH).
119
+
120
+ ### Typescript Type Issue
121
+
122
+ When working with packages that are not officially supported by `hono-rate-limiter`, you might encounter type-related issues. These can be easily resolved by referring to the discussions in [#22](https://github.com/rhinobase/hono-rate-limiter/issues/22), [#10](https://github.com/rhinobase/hono-rate-limiter/issues/10). Example -
123
+
124
+ ```ts
125
+ rateLimiter({
126
+ // ...
127
+ store: new RedisStore({
128
+ sendCommand: (...args: string[]) => redisClient.sendCommand(args),
129
+ }) as unknown as Store,
130
+ });
131
+ ```
132
+
133
+ ### Using `hono-rate-limiter` with Cloudflare Workers or Pages
134
+
135
+ If you're trying to use `hono-rate-limiter` in a Cloudflare environment (such as Workers or Pages), you may encounter the following error:
136
+
137
+ ```bash
138
+ Uncaught Error: Disallowed operation called within global scope. Asynchronous I/O (ex: fetch() or connect()), setting a timeout, and generating random values are not allowed within global scope. To fix this error, perform this operation within a handler. https://developers.cloudflare.com/workers/runtime-apis/handlers/
139
+ ```
140
+
141
+ This happens because the default memory store used by `hono-rate-limiter` cannot run in the Cloudflare environment due to its restrictions on global asynchronous operations.
142
+
143
+ #### Solution
144
+
145
+ To resolve this issue, you need to use a compatible store for Cloudflare. You can use the [`@hono-rate-limiter/cloudflare`](https://www.npmjs.com/package/@hono-rate-limiter/cloudflare) package, which is specifically designed to work with Cloudflare's infrastructure.
146
+
147
+ ## Contributing
148
+
149
+ We would love to have more contributors involved!
150
+
151
+ To get started, please read our [Contributing Guide](https://github.com/rhinobase/hono-rate-limiter/blob/main/CONTRIBUTING.md).
152
+
153
+ ## Credits
154
+
155
+ The `hono-rate-limiter` project is heavily inspired by [express-rate-limit](https://github.com/express-rate-limit/express-rate-limit)
package/index.cjs.d.ts CHANGED
@@ -1 +1 @@
1
- export * from "./src\\index";
1
+ export * from "./src/index";
package/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("hono/factory");const t=(e,t)=>{let i;if(e){const t=Math.ceil((e.getTime()-Date.now())/1e3);i=Math.max(0,t)}else t&&(i=Math.ceil(t/1e3));return i};class i{init(e){this.windowMs=e.windowMs,this.interval&&clearInterval(this.interval),this.interval=setInterval((()=>{this.clearExpired()}),this.windowMs),this.interval.unref&&this.interval.unref()}async get(e){return this.current.get(e)??this.previous.get(e)}async increment(e){const t=this.getClient(e),i=Date.now();return t.resetTime.getTime()<=i&&this.resetClient(t,i),t.totalHits++,t}async decrement(e){const t=this.getClient(e);t.totalHits>0&&t.totalHits--}async resetKey(e){this.current.delete(e),this.previous.delete(e)}async resetAll(){this.current.clear(),this.previous.clear()}shutdown(){clearInterval(this.interval),this.resetAll()}resetClient(e,t=Date.now()){return e.totalHits=0,e.resetTime.setTime(t+this.windowMs),e}getClient(e){const t=this.current.get(e);if(t)return t;let i;const s=this.previous.get(e);return s?(i=s,this.previous.delete(e)):(i={totalHits:0,resetTime:new Date},this.resetClient(i)),this.current.set(e,i),i}clearExpired(){this.previous=this.current,this.current=new Map}constructor(){this.previous=new Map,this.current=new Map,this.localKeys=!0}}const s=e=>!!e?.increment;function r(e,t){if(!s(e))throw new Error("The store is not correctly implemented!");"function"==typeof e.init&&e.init(t)}async function a(e,t,i){const s=await t(e),{totalHits:r,resetTime:a}=await i.increment(s);return{key:s,totalHits:r,resetTime:a}}exports.rateLimiter=function(s){const{windowMs:n=6e4,limit:o=5,message:c="Too many requests, please try again later.",statusCode:l=429,standardHeaders:u="draft-6",requestPropertyName:m="rateLimit",requestStorePropertyName:d="rateLimitStore",skipFailedRequests:w=!1,skipSuccessfulRequests:y=!1,keyGenerator:h,skip:f=(()=>!1),requestWasSuccessful:p=(e=>e.res.status<400),handler:g=(async(e,t,i)=>{e.status(i.statusCode);const s="function"==typeof i.message?await i.message(e):i.message;return"string"==typeof s?e.text(s):e.json(s)}),store:M=new i}=s,q={windowMs:n,limit:o,message:c,statusCode:l,standardHeaders:u,requestPropertyName:m,requestStorePropertyName:d,skipFailedRequests:w,skipSuccessfulRequests:y,keyGenerator:h,skip:f,requestWasSuccessful:p,handler:g,store:M};return r(M,q),e.createMiddleware((async(e,i)=>{if(await f(e))return void await i();const{key:s,totalHits:r,resetTime:c}=await a(e,h,M),l="function"==typeof o?o(e):o,k=await l,v={limit:k,used:r,remaining:Math.max(k-r,0),resetTime:c};e.set(m,v),e.set(d,{getKey:M.get?.bind(M),resetKey:M.resetKey.bind(M)}),u&&!e.finalized&&("draft-7"===u?((e,i,s)=>{if(e.finalized)return;const r=Math.ceil(s/1e3),a=t(i.resetTime,s);e.header("RateLimit-Policy",`${i.limit};w=${r}`),e.header("RateLimit",`limit=${i.limit}, remaining=${i.remaining}, reset=${a}`)})(e,v,n):((e,i,s)=>{if(e.finalized)return;const r=Math.ceil(s/1e3),a=t(i.resetTime);e.header("RateLimit-Policy",`${i.limit};w=${r}`),e.header("RateLimit-Limit",i.limit.toString()),e.header("RateLimit-Remaining",i.remaining.toString()),a&&e.header("RateLimit-Reset",a.toString())})(e,v,n));let T=!1;const R=async()=>{T||(await M.decrement(s),T=!0)},S=async()=>{if(w||y){const t=await p(e);(w&&!t||y&&t)&&await R()}};if(r>k)return u&&((e,i,s)=>{if(e.finalized)return;const r=t(i.resetTime,s);e.header("Retry-After",r?.toString())})(e,v,n),await S(),g(e,i,q);try{await i(),await S()}catch(e){w&&await R()}finally{e.finalized||await R()}}))},exports.webSocketLimiter=function(e){const{windowMs:t=6e4,limit:s=5,message:n="Too many requests, please try again later.",statusCode:o=1008,requestPropertyName:c="rateLimit",requestStorePropertyName:l="rateLimitStore",skipFailedRequests:u=!1,skipSuccessfulRequests:m=!1,keyGenerator:d,skip:w=(()=>!1),handler:y=(async(e,t,i)=>t.close(i.statusCode,i.message)),store:h=new i}=e,f={windowMs:t,limit:s,message:n,statusCode:o,requestPropertyName:c,requestStorePropertyName:l,skipFailedRequests:u,skipSuccessfulRequests:m,keyGenerator:d,skip:w,handler:y,store:h};return r(h,f),e=>async t=>{const i=await e(t);return{...i,onMessage:async(e,r)=>{if(await w(e,r))return void await(i.onMessage?.(e,r));const{key:n,totalHits:o,resetTime:p}=await a(t,d,h),g="function"==typeof s?s(t):s,M=await g,q={limit:M,used:o,remaining:Math.max(M-o,0),resetTime:p};t.set(c,q),t.set(l,{getKey:h.get?.bind(h),resetKey:h.resetKey.bind(h)});let k=!1;const v=async()=>{k||(await h.decrement(n),k=!0)},T=async()=>{m&&await v()};if(o>M)return await T(),y(e,r,f);try{await(i.onMessage?.(e,r)),await T()}catch(e){u&&await v()}},onError:async(e,s)=>{if(u){const e=await d(t);await h.decrement(e)}i.onError?.(e,s)}}}};
1
+ "use strict";const e=(e,t)=>{let i;if(e){const t=Math.ceil((e.getTime()-Date.now())/1e3);i=Math.max(0,t)}else t&&(i=Math.ceil(t/1e3));return i};class t{#e;init(e){this.#e=e.windowMs,this.interval&&clearInterval(this.interval),this.interval=setInterval((()=>{this.clearExpired()}),this.#e),this.interval.unref&&this.interval.unref()}get(e){return this.current.get(e)??this.previous.get(e)}increment(e){const t=this.getClient(e),i=Date.now();return t.resetTime.getTime()<=i&&this.resetClient(t,i),t.totalHits++,t}decrement(e){const t=this.getClient(e);t.totalHits>0&&t.totalHits--}resetKey(e){this.current.delete(e),this.previous.delete(e)}resetAll(){this.current.clear(),this.previous.clear()}shutdown(){clearInterval(this.interval),this.resetAll()}resetClient(e,t=Date.now()){return e.totalHits=0,e.resetTime.setTime(t+this.#e),e}getClient(e){const t=this.current.get(e);if(t)return t;let i;const s=this.previous.get(e);return s?(i=s,this.previous.delete(e)):(i={totalHits:0,resetTime:new Date},this.resetClient(i)),this.current.set(e,i),i}clearExpired(){this.previous=this.current,this.current=new Map}constructor(){this.previous=new Map,this.current=new Map}}const i=e=>!!e?.increment;function s(e,t){if(!i(e))throw new Error("The store is not correctly implemented!");"function"==typeof e.init&&e.init(t)}async function r(e,t,i){const s=await t(e),{totalHits:r,resetTime:a}=await i.increment(s);return{key:s,totalHits:r,resetTime:a}}exports.rateLimiter=function(i){const{windowMs:a=6e4,limit:n=5,message:o="Too many requests, please try again later.",statusCode:c=429,standardHeaders:l="draft-6",requestPropertyName:u="rateLimit",requestStorePropertyName:m="rateLimitStore",skipFailedRequests:d=!1,skipSuccessfulRequests:w=!1,keyGenerator:h,skip:y=(()=>!1),requestWasSuccessful:f=(e=>e.res.status<400),handler:p=(async(e,t,i)=>{e.status(i.statusCode);const s="function"==typeof i.message?await i.message(e):i.message;return"string"==typeof s?e.text(s):e.json(s)}),store:g=new t}=i,M={windowMs:a,limit:n,message:o,statusCode:c,standardHeaders:l,requestPropertyName:u,requestStorePropertyName:m,skipFailedRequests:d,skipSuccessfulRequests:w,keyGenerator:h,skip:y,requestWasSuccessful:f,handler:p,store:g};return s(g,M),async(t,i)=>{if(await y(t))return void await i();const{key:s,totalHits:o,resetTime:c}=await r(t,h,g),k="function"==typeof n?n(t):n,q=await k,v={limit:q,used:o,remaining:Math.max(q-o,0),resetTime:c};t.set(u,v),t.set(m,{getKey:g.get?.bind(g),resetKey:g.resetKey.bind(g)}),l&&!t.finalized&&("draft-7"===l?((t,i,s)=>{if(t.finalized)return;const r=Math.ceil(s/1e3),a=e(i.resetTime,s);t.header("RateLimit-Policy",`${i.limit};w=${r}`),t.header("RateLimit",`limit=${i.limit}, remaining=${i.remaining}, reset=${a}`)})(t,v,a):((t,i,s)=>{if(t.finalized)return;const r=Math.ceil(s/1e3),a=e(i.resetTime);t.header("RateLimit-Policy",`${i.limit};w=${r}`),t.header("RateLimit-Limit",i.limit.toString()),t.header("RateLimit-Remaining",i.remaining.toString()),a&&t.header("RateLimit-Reset",a.toString())})(t,v,a));let T=!1;const R=async()=>{T||(await g.decrement(s),T=!0)},S=async()=>{if(d||w){const e=await f(t);(d&&!e||w&&e)&&await R()}};if(o>q)return l&&((t,i,s)=>{if(t.finalized)return;const r=e(i.resetTime,s);t.header("Retry-After",r?.toString())})(t,v,a),await S(),p(t,i,M);try{await i(),await S()}catch(e){d&&await R()}finally{t.finalized||await R()}}},exports.webSocketLimiter=function(e){const{windowMs:i=6e4,limit:a=5,message:n="Too many requests, please try again later.",statusCode:o=1008,requestPropertyName:c="rateLimit",requestStorePropertyName:l="rateLimitStore",skipFailedRequests:u=!1,skipSuccessfulRequests:m=!1,keyGenerator:d,skip:w=(()=>!1),handler:h=(async(e,t,i)=>t.close(i.statusCode,i.message)),store:y=new t}=e,f={windowMs:i,limit:a,message:n,statusCode:o,requestPropertyName:c,requestStorePropertyName:l,skipFailedRequests:u,skipSuccessfulRequests:m,keyGenerator:d,skip:w,handler:h,store:y};return s(y,f),e=>async t=>{const i=await e(t);return{...i,onMessage:async(e,s)=>{if(await w(e,s))return void await(i.onMessage?.(e,s));const{key:n,totalHits:o,resetTime:p}=await r(t,d,y),g="function"==typeof a?a(t):a,M=await g,k={limit:M,used:o,remaining:Math.max(M-o,0),resetTime:p};t.set(c,k),t.set(l,{getKey:y.get?.bind(y),resetKey:y.resetKey.bind(y)});let q=!1;const v=async()=>{q||(await y.decrement(n),q=!0)},T=async()=>{m&&await v()};if(o>M)return await T(),h(e,s,f);try{await(i.onMessage?.(e,s)),await T()}catch(e){u&&await v()}},onError:async(e,s)=>{if(u){const e=await d(t);await y.decrement(e)}i.onError?.(e,s)}}}};
package/index.esm.d.ts CHANGED
@@ -1 +1 @@
1
- export * from "./src\\index";
1
+ export * from "./src/index";
package/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{createMiddleware as e}from"hono/factory";const t=(e,t)=>{let i;if(e){const t=Math.ceil((e.getTime()-Date.now())/1e3);i=Math.max(0,t)}else t&&(i=Math.ceil(t/1e3));return i};class i{init(e){this.windowMs=e.windowMs,this.interval&&clearInterval(this.interval),this.interval=setInterval((()=>{this.clearExpired()}),this.windowMs),this.interval.unref&&this.interval.unref()}async get(e){return this.current.get(e)??this.previous.get(e)}async increment(e){const t=this.getClient(e),i=Date.now();return t.resetTime.getTime()<=i&&this.resetClient(t,i),t.totalHits++,t}async decrement(e){const t=this.getClient(e);t.totalHits>0&&t.totalHits--}async resetKey(e){this.current.delete(e),this.previous.delete(e)}async resetAll(){this.current.clear(),this.previous.clear()}shutdown(){clearInterval(this.interval),this.resetAll()}resetClient(e,t=Date.now()){return e.totalHits=0,e.resetTime.setTime(t+this.windowMs),e}getClient(e){const t=this.current.get(e);if(t)return t;let i;const s=this.previous.get(e);return s?(i=s,this.previous.delete(e)):(i={totalHits:0,resetTime:new Date},this.resetClient(i)),this.current.set(e,i),i}clearExpired(){this.previous=this.current,this.current=new Map}constructor(){this.previous=new Map,this.current=new Map,this.localKeys=!0}}const s=e=>!!e?.increment;function r(e,t){if(!s(e))throw new Error("The store is not correctly implemented!");"function"==typeof e.init&&e.init(t)}async function a(e,t,i){const s=await t(e),{totalHits:r,resetTime:a}=await i.increment(s);return{key:s,totalHits:r,resetTime:a}}function n(s){const{windowMs:n=6e4,limit:o=5,message:c="Too many requests, please try again later.",statusCode:l=429,standardHeaders:u="draft-6",requestPropertyName:m="rateLimit",requestStorePropertyName:d="rateLimitStore",skipFailedRequests:w=!1,skipSuccessfulRequests:y=!1,keyGenerator:h,skip:f=(()=>!1),requestWasSuccessful:p=(e=>e.res.status<400),handler:g=(async(e,t,i)=>{e.status(i.statusCode);const s="function"==typeof i.message?await i.message(e):i.message;return"string"==typeof s?e.text(s):e.json(s)}),store:M=new i}=s,q={windowMs:n,limit:o,message:c,statusCode:l,standardHeaders:u,requestPropertyName:m,requestStorePropertyName:d,skipFailedRequests:w,skipSuccessfulRequests:y,keyGenerator:h,skip:f,requestWasSuccessful:p,handler:g,store:M};return r(M,q),e((async(e,i)=>{if(await f(e))return void await i();const{key:s,totalHits:r,resetTime:c}=await a(e,h,M),l="function"==typeof o?o(e):o,k=await l,v={limit:k,used:r,remaining:Math.max(k-r,0),resetTime:c};e.set(m,v),e.set(d,{getKey:M.get?.bind(M),resetKey:M.resetKey.bind(M)}),u&&!e.finalized&&("draft-7"===u?((e,i,s)=>{if(e.finalized)return;const r=Math.ceil(s/1e3),a=t(i.resetTime,s);e.header("RateLimit-Policy",`${i.limit};w=${r}`),e.header("RateLimit",`limit=${i.limit}, remaining=${i.remaining}, reset=${a}`)})(e,v,n):((e,i,s)=>{if(e.finalized)return;const r=Math.ceil(s/1e3),a=t(i.resetTime);e.header("RateLimit-Policy",`${i.limit};w=${r}`),e.header("RateLimit-Limit",i.limit.toString()),e.header("RateLimit-Remaining",i.remaining.toString()),a&&e.header("RateLimit-Reset",a.toString())})(e,v,n));let T=!1;const R=async()=>{T||(await M.decrement(s),T=!0)},S=async()=>{if(w||y){const t=await p(e);(w&&!t||y&&t)&&await R()}};if(r>k)return u&&((e,i,s)=>{if(e.finalized)return;const r=t(i.resetTime,s);e.header("Retry-After",r?.toString())})(e,v,n),await S(),g(e,i,q);try{await i(),await S()}catch(e){w&&await R()}finally{e.finalized||await R()}}))}function o(e){const{windowMs:t=6e4,limit:s=5,message:n="Too many requests, please try again later.",statusCode:o=1008,requestPropertyName:c="rateLimit",requestStorePropertyName:l="rateLimitStore",skipFailedRequests:u=!1,skipSuccessfulRequests:m=!1,keyGenerator:d,skip:w=(()=>!1),handler:y=(async(e,t,i)=>t.close(i.statusCode,i.message)),store:h=new i}=e,f={windowMs:t,limit:s,message:n,statusCode:o,requestPropertyName:c,requestStorePropertyName:l,skipFailedRequests:u,skipSuccessfulRequests:m,keyGenerator:d,skip:w,handler:y,store:h};return r(h,f),e=>async t=>{const i=await e(t);return{...i,onMessage:async(e,r)=>{if(await w(e,r))return void await(i.onMessage?.(e,r));const{key:n,totalHits:o,resetTime:p}=await a(t,d,h),g="function"==typeof s?s(t):s,M=await g,q={limit:M,used:o,remaining:Math.max(M-o,0),resetTime:p};t.set(c,q),t.set(l,{getKey:h.get?.bind(h),resetKey:h.resetKey.bind(h)});let k=!1;const v=async()=>{k||(await h.decrement(n),k=!0)},T=async()=>{m&&await v()};if(o>M)return await T(),y(e,r,f);try{await(i.onMessage?.(e,r)),await T()}catch(e){u&&await v()}},onError:async(e,s)=>{if(u){const e=await d(t);await h.decrement(e)}i.onError?.(e,s)}}}}export{n as rateLimiter,o as webSocketLimiter};
1
+ const e=(e,t)=>{let i;if(e){const t=Math.ceil((e.getTime()-Date.now())/1e3);i=Math.max(0,t)}else t&&(i=Math.ceil(t/1e3));return i};class t{#e;init(e){this.#e=e.windowMs,this.interval&&clearInterval(this.interval),this.interval=setInterval((()=>{this.clearExpired()}),this.#e),this.interval.unref&&this.interval.unref()}get(e){return this.current.get(e)??this.previous.get(e)}increment(e){const t=this.getClient(e),i=Date.now();return t.resetTime.getTime()<=i&&this.resetClient(t,i),t.totalHits++,t}decrement(e){const t=this.getClient(e);t.totalHits>0&&t.totalHits--}resetKey(e){this.current.delete(e),this.previous.delete(e)}resetAll(){this.current.clear(),this.previous.clear()}shutdown(){clearInterval(this.interval),this.resetAll()}resetClient(e,t=Date.now()){return e.totalHits=0,e.resetTime.setTime(t+this.#e),e}getClient(e){const t=this.current.get(e);if(t)return t;let i;const s=this.previous.get(e);return s?(i=s,this.previous.delete(e)):(i={totalHits:0,resetTime:new Date},this.resetClient(i)),this.current.set(e,i),i}clearExpired(){this.previous=this.current,this.current=new Map}constructor(){this.previous=new Map,this.current=new Map}}const i=e=>!!e?.increment;function s(e,t){if(!i(e))throw new Error("The store is not correctly implemented!");"function"==typeof e.init&&e.init(t)}async function r(e,t,i){const s=await t(e),{totalHits:r,resetTime:a}=await i.increment(s);return{key:s,totalHits:r,resetTime:a}}function a(i){const{windowMs:a=6e4,limit:n=5,message:o="Too many requests, please try again later.",statusCode:c=429,standardHeaders:l="draft-6",requestPropertyName:u="rateLimit",requestStorePropertyName:m="rateLimitStore",skipFailedRequests:d=!1,skipSuccessfulRequests:w=!1,keyGenerator:h,skip:y=(()=>!1),requestWasSuccessful:f=(e=>e.res.status<400),handler:p=(async(e,t,i)=>{e.status(i.statusCode);const s="function"==typeof i.message?await i.message(e):i.message;return"string"==typeof s?e.text(s):e.json(s)}),store:g=new t}=i,M={windowMs:a,limit:n,message:o,statusCode:c,standardHeaders:l,requestPropertyName:u,requestStorePropertyName:m,skipFailedRequests:d,skipSuccessfulRequests:w,keyGenerator:h,skip:y,requestWasSuccessful:f,handler:p,store:g};return s(g,M),async(t,i)=>{if(await y(t))return void await i();const{key:s,totalHits:o,resetTime:c}=await r(t,h,g),q="function"==typeof n?n(t):n,k=await q,v={limit:k,used:o,remaining:Math.max(k-o,0),resetTime:c};t.set(u,v),t.set(m,{getKey:g.get?.bind(g),resetKey:g.resetKey.bind(g)}),l&&!t.finalized&&("draft-7"===l?((t,i,s)=>{if(t.finalized)return;const r=Math.ceil(s/1e3),a=e(i.resetTime,s);t.header("RateLimit-Policy",`${i.limit};w=${r}`),t.header("RateLimit",`limit=${i.limit}, remaining=${i.remaining}, reset=${a}`)})(t,v,a):((t,i,s)=>{if(t.finalized)return;const r=Math.ceil(s/1e3),a=e(i.resetTime);t.header("RateLimit-Policy",`${i.limit};w=${r}`),t.header("RateLimit-Limit",i.limit.toString()),t.header("RateLimit-Remaining",i.remaining.toString()),a&&t.header("RateLimit-Reset",a.toString())})(t,v,a));let T=!1;const R=async()=>{T||(await g.decrement(s),T=!0)},S=async()=>{if(d||w){const e=await f(t);(d&&!e||w&&e)&&await R()}};if(o>k)return l&&((t,i,s)=>{if(t.finalized)return;const r=e(i.resetTime,s);t.header("Retry-After",r?.toString())})(t,v,a),await S(),p(t,i,M);try{await i(),await S()}catch(e){d&&await R()}finally{t.finalized||await R()}}}function n(e){const{windowMs:i=6e4,limit:a=5,message:n="Too many requests, please try again later.",statusCode:o=1008,requestPropertyName:c="rateLimit",requestStorePropertyName:l="rateLimitStore",skipFailedRequests:u=!1,skipSuccessfulRequests:m=!1,keyGenerator:d,skip:w=(()=>!1),handler:h=(async(e,t,i)=>t.close(i.statusCode,i.message)),store:y=new t}=e,f={windowMs:i,limit:a,message:n,statusCode:o,requestPropertyName:c,requestStorePropertyName:l,skipFailedRequests:u,skipSuccessfulRequests:m,keyGenerator:d,skip:w,handler:h,store:y};return s(y,f),e=>async t=>{const i=await e(t);return{...i,onMessage:async(e,s)=>{if(await w(e,s))return void await(i.onMessage?.(e,s));const{key:n,totalHits:o,resetTime:p}=await r(t,d,y),g="function"==typeof a?a(t):a,M=await g,q={limit:M,used:o,remaining:Math.max(M-o,0),resetTime:p};t.set(c,q),t.set(l,{getKey:y.get?.bind(y),resetKey:y.resetKey.bind(y)});let k=!1;const v=async()=>{k||(await y.decrement(n),k=!0)},T=async()=>{m&&await v()};if(o>M)return await T(),h(e,s,f);try{await(i.onMessage?.(e,s)),await T()}catch(e){u&&await v()}},onError:async(e,s)=>{if(u){const e=await d(t);await y.decrement(e)}i.onError?.(e,s)}}}}export{a as rateLimiter,n as webSocketLimiter};
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "hono-rate-limiter",
3
- "version": "0.4.0",
3
+ "description": "Rate limit middleware for Hono.",
4
+ "version": "0.4.1",
4
5
  "license": "MIT",
5
6
  "keywords": [
6
7
  "hono",
package/src/core.d.ts CHANGED
@@ -4,7 +4,7 @@ import type { ConfigType, GeneralConfigType } from "./types";
4
4
  *
5
5
  * Create an instance of rate-limiting middleware for Hono.
6
6
  *
7
- * @param config x{ConfigType} - Options to configure the rate limiter.
7
+ * @param config {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/store.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import type { Env, Input } from "hono/types";
3
2
  import type { ClientRateLimitInfo, ConfigType, Store, WSConfigType } from "./types";
4
3
  /**
@@ -7,10 +6,7 @@ import type { ClientRateLimitInfo, ConfigType, Store, WSConfigType } from "./typ
7
6
  * @public
8
7
  */
9
8
  export declare class MemoryStore<E extends Env = Env, P extends string = string, I extends Input = Input> implements Store<E, P, I> {
10
- /**
11
- * The duration of time before which all hit counts are reset (in milliseconds).
12
- */
13
- windowMs: number;
9
+ #private;
14
10
  /**
15
11
  * These two maps store usage (requests) and reset time by key (for example, IP
16
12
  * addresses or API keys).
@@ -26,12 +22,7 @@ export declare class MemoryStore<E extends Env = Env, P extends string = string,
26
22
  /**
27
23
  * A reference to the active timer.
28
24
  */
29
- interval?: NodeJS.Timeout;
30
- /**
31
- * Confirmation that the keys incremented in once instance of MemoryStore
32
- * cannot affect other instances.
33
- */
34
- localKeys: boolean;
25
+ interval?: any;
35
26
  /**
36
27
  * Method that initializes the store.
37
28
  *
@@ -47,7 +38,7 @@ export declare class MemoryStore<E extends Env = Env, P extends string = string,
47
38
  *
48
39
  * @public
49
40
  */
50
- get(key: string): Promise<ClientRateLimitInfo | undefined>;
41
+ get(key: string): ClientRateLimitInfo | undefined;
51
42
  /**
52
43
  * Method to increment a client's hit counter.
53
44
  *
@@ -57,7 +48,7 @@ export declare class MemoryStore<E extends Env = Env, P extends string = string,
57
48
  *
58
49
  * @public
59
50
  */
60
- increment(key: string): Promise<ClientRateLimitInfo>;
51
+ increment(key: string): ClientRateLimitInfo;
61
52
  /**
62
53
  * Method to decrement a client's hit counter.
63
54
  *
@@ -65,7 +56,7 @@ export declare class MemoryStore<E extends Env = Env, P extends string = string,
65
56
  *
66
57
  * @public
67
58
  */
68
- decrement(key: string): Promise<void>;
59
+ decrement(key: string): void;
69
60
  /**
70
61
  * Method to reset a client's hit counter.
71
62
  *
@@ -73,13 +64,13 @@ export declare class MemoryStore<E extends Env = Env, P extends string = string,
73
64
  *
74
65
  * @public
75
66
  */
76
- resetKey(key: string): Promise<void>;
67
+ resetKey(key: string): void;
77
68
  /**
78
69
  * Method to reset everyone's hit counter.
79
70
  *
80
71
  * @public
81
72
  */
82
- resetAll(): Promise<void>;
73
+ resetAll(): void;
83
74
  /**
84
75
  * Method to stop the timer (if currently running) and prevent any memory
85
76
  * leaks.