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 +155 -119
- package/index.cjs.d.ts +1 -1
- package/index.cjs.js +1 -1
- package/index.esm.d.ts +1 -1
- package/index.esm.js +1 -1
- package/package.json +2 -1
- package/src/core.d.ts +1 -1
- package/src/store.d.ts +7 -16
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
|
-
[](https://github.com/rhinobase/hono-rate-limiter/actions/workflows/test.yml)
|
|
6
|
-
[](https://npmjs.org/package/hono-rate-limiter "View this project on NPM")
|
|
7
|
-
[](https://www.npmjs.com/package/hono-rate-limiter)
|
|
8
|
-
[](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
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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
|
|
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
|
|
92
|
-
|
|
|
93
|
-
| MemoryStore
|
|
94
|
-
| [
|
|
95
|
-
| [
|
|
96
|
-
| [
|
|
97
|
-
| [
|
|
98
|
-
| [
|
|
99
|
-
| [
|
|
100
|
-
| [
|
|
101
|
-
| [
|
|
102
|
-
| [
|
|
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
|
-
##
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
1
|
+
<h1 align="center"> <code>🔥hono-rate-limiter🔥</code> </h1>
|
|
2
|
+
|
|
3
|
+
<div align="center">
|
|
4
|
+
|
|
5
|
+
[](https://github.com/rhinobase/hono-rate-limiter/actions/workflows/test.yml)
|
|
6
|
+
[](https://npmjs.org/package/hono-rate-limiter "View this project on NPM")
|
|
7
|
+
[](https://www.npmjs.com/package/hono-rate-limiter)
|
|
8
|
+
[](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) . [](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. [](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
|
|
1
|
+
export * from "./src/index";
|
package/index.cjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";
|
|
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
|
|
1
|
+
export * from "./src/index";
|
package/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
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
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
|
|
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?:
|
|
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):
|
|
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):
|
|
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):
|
|
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):
|
|
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():
|
|
73
|
+
resetAll(): void;
|
|
83
74
|
/**
|
|
84
75
|
* Method to stop the timer (if currently running) and prevent any memory
|
|
85
76
|
* leaks.
|