@clov-std/elysia-ratelimit 1.2.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/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Clov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ <p align="center">
2
+ <img src="https://cdn.jsdelivr.net/gh/ClovLabs/std@main/packages/elysia-ratelimit/logo-elysia-ratelimit.png" alt="Clov Elysia Rate Limit logo" width="200" />
3
+ </p>
4
+
5
+ # 🚦 Clov Elysia Rate Limit
6
+
7
+ Rate limiting for Elysia routes, guards, and groups, as a macro.
8
+ Drop `rateLimit` on any endpoint and abusive traffic gets cut before it ever hits your logic.
9
+
10
+ ## Why this package?
11
+
12
+ This plugin uses Elysia's macro system to add rate limiting to any route, guard, or group.
13
+ You add `rateLimit: { limit: 10, window: 60 }` and you're done.
14
+
15
+ By default it limits by client IP, which works great for auth endpoints.
16
+ For cases where many users share the same public IP (offices, corporate proxies), you can pass a `keyGenerator` to rate limit by IP + access token, session ID, API key, or any combination that makes sense.
17
+
18
+ Storage is handled by `@clov-std/kv-store`, so you start with in-memory and move to Redis when you need to, without changing your routes.
19
+
20
+ ## 📌 Table of Contents
21
+
22
+ - [Features](#-features)
23
+ - [Installation](#-installation)
24
+ - [Usage](#-usage)
25
+ - [API Reference](#-api-reference)
26
+ - [License](#-license)
27
+ - [Contact](#-contact)
28
+
29
+ ## ✨ Features
30
+
31
+ - 🎯 **Per-route macros** : Attach `rateLimit` to any route independently, with its own `limit` and `window`.
32
+ - 🔑 **Custom key generation** : Rate limit by IP (default), IP + token, session, or any key you compute.
33
+ - 🗃️ **KvStore-agnostic** : Works with `MemoryStore` out of the box; swap in `BunRedisStore` or your own adapter.
34
+ - ⚡ **Early rejection** : Runs in `transform`, the first per-route hook, before auth guards and handlers.
35
+ - 📡 **Standard headers** : Automatically sets `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset`.
36
+
37
+ ## 🔧 Installation
38
+
39
+ ```bash
40
+ bun add @clov-std/elysia-ratelimit
41
+ ```
42
+
43
+ > **Peer dependencies:** `elysia` must be installed alongside.
44
+
45
+ ## ⚙️ Usage
46
+
47
+ ### Basic - rate limit by IP
48
+
49
+ The simplest form: pass `limit` (max requests) and `window` (time in seconds). Each client IP gets its own counter.
50
+
51
+ ```ts
52
+ import { rateLimitPlugin } from '@clov-std/elysia-ratelimit';
53
+ import { Elysia } from 'elysia';
54
+
55
+ new Elysia()
56
+ .use(rateLimitPlugin())
57
+ .post('/auth/login', () => authenticate(), {
58
+ rateLimit: { limit: 10, window: 60 } // 10 requests per minute per IP
59
+ })
60
+ .listen(3000);
61
+ ```
62
+
63
+ ### Custom store - Redis
64
+
65
+ By default, counters are kept in memory. Pass a `BunRedisStore` (or any `KvStore` adapter) for persistence across restarts and multi-instance deployments.
66
+
67
+ ```ts
68
+ import { BunRedisStore } from '@clov-std/kv-store';
69
+ import { rateLimitPlugin } from '@clov-std/elysia-ratelimit';
70
+ import { Elysia } from 'elysia';
71
+
72
+ const store = new BunRedisStore('redis://localhost:6379');
73
+
74
+ new Elysia()
75
+ .use(rateLimitPlugin(store))
76
+ .post('/auth/login', () => authenticate(), {
77
+ rateLimit: { limit: 10, window: 60 }
78
+ })
79
+ .listen(3000);
80
+ ```
81
+
82
+ ### Custom key generation - IP + access token
83
+
84
+ Useful for authenticated routes where many users share the same public IP (office, corporate proxy).
85
+ Each user has their own counter, independent of their network.
86
+
87
+ ```ts
88
+ import { rateLimitPlugin } from '@clov-std/elysia-ratelimit';
89
+ import { Elysia } from 'elysia';
90
+
91
+ new Elysia()
92
+ .use(rateLimitPlugin())
93
+ .get('/api/data', () => getData(), {
94
+ rateLimit: {
95
+ limit: 100,
96
+ window: 60,
97
+ keyGenerator: ({ ip, request }) => `${ip}:${request.headers.get('authorization') ?? ip}`
98
+ }
99
+ })
100
+ .listen(3000);
101
+ ```
102
+
103
+ > **Tip:** `extractClientIp` is exported if you need it inside your own `keyGenerator`.
104
+
105
+ ## 📚 API Reference
106
+
107
+ Full docs: [https://clovlabs.github.io/std/](https://clovlabs.github.io/std/)
108
+
109
+ ## ⚖️ License
110
+
111
+ MIT — see [LICENSE.md](LICENSE.md).
112
+
113
+ ## 📧 Contact
114
+
115
+ Maintained by [Clov](https://github.com/ClovLabs).
@@ -0,0 +1,2 @@
1
+ export { extractClientIp, RATE_LIMIT_ERROR_KEYS, rateLimitPlugin, type RateLimitKeyContext, type RateLimitMacroOptions } from './rate-limit';
2
+ export { rateLimitContract } from './rate-limit.contract';
package/dist/index.js ADDED
@@ -0,0 +1,69 @@
1
+ // @bun
2
+ // src/rate-limit.ts
3
+ import { HttpException } from "@clov-std/error";
4
+ import { MemoryStore } from "@clov-std/kv-store";
5
+ import { Elysia } from "elysia";
6
+
7
+ // src/rate-limit.contract.ts
8
+ import { t } from "elysia";
9
+ var rateLimitContract = {
10
+ 429: t.Object({
11
+ message: t.String({
12
+ description: "Error message indicating that the rate limit has been exceeded."
13
+ })
14
+ })
15
+ };
16
+
17
+ // src/rate-limit.ts
18
+ var RATE_LIMIT_ERROR_KEYS = {
19
+ RATE_LIMIT_EXCEEDED: "elysia-ratelimit.exceeded"
20
+ };
21
+ var extractClientIp = (request, server) => {
22
+ const forwarded = request.headers.get("x-forwarded-for");
23
+ if (forwarded) {
24
+ const [first] = forwarded.split(",");
25
+ if (first)
26
+ return first.trim();
27
+ }
28
+ return request.headers.get("x-real-ip") ?? server?.requestIP(request)?.address ?? "127.0.0.1";
29
+ };
30
+ var rateLimitPlugin = (store = new MemoryStore) => new Elysia({
31
+ name: "rateLimitPlugin",
32
+ seed: store
33
+ }).model({
34
+ RateLimitError: rateLimitContract[429]
35
+ }).macro({
36
+ rateLimit: ({ limit, window, keyGenerator }) => ({
37
+ response: {
38
+ 429: "RateLimitError"
39
+ },
40
+ transform: async ({ set, request, server }) => {
41
+ const route = `${request.method}:${new URL(request.url).pathname}`;
42
+ const ip = extractClientIp(request, server);
43
+ const discriminator = keyGenerator ? keyGenerator({ request, server, ip }) : ip;
44
+ const key = `ratelimit:${route}:${discriminator}`;
45
+ const count = await store.increment(key);
46
+ if (count === 1)
47
+ await store.expire(key, window);
48
+ const remaining = Math.max(0, limit - count);
49
+ const resetTime = await store.ttl(key);
50
+ set.headers["X-RateLimit-Limit"] = limit.toString();
51
+ set.headers["X-RateLimit-Remaining"] = remaining.toString();
52
+ set.headers["X-RateLimit-Reset"] = resetTime.toString();
53
+ if (count > limit) {
54
+ set.status = 429;
55
+ throw new HttpException("Too Many Requests", {
56
+ key: RATE_LIMIT_ERROR_KEYS.RATE_LIMIT_EXCEEDED,
57
+ cause: { limit, window, remaining: 0, reset: resetTime },
58
+ status: 429
59
+ });
60
+ }
61
+ }
62
+ })
63
+ });
64
+ export {
65
+ rateLimitPlugin,
66
+ rateLimitContract,
67
+ extractClientIp,
68
+ RATE_LIMIT_ERROR_KEYS
69
+ };
@@ -0,0 +1,5 @@
1
+ export declare const rateLimitContract: {
2
+ 429: import("@sinclair/typebox").TObject<{
3
+ message: import("@sinclair/typebox").TString;
4
+ }>;
5
+ };
@@ -0,0 +1,52 @@
1
+ import { type KvStore } from '@clov-std/kv-store';
2
+ import type { Server } from 'bun';
3
+ import { Elysia, type HTTPHeaders, type StatusMap } from 'elysia';
4
+ import { rateLimitContract } from './rate-limit.contract';
5
+ export declare const RATE_LIMIT_ERROR_KEYS: {
6
+ readonly RATE_LIMIT_EXCEEDED: "elysia-ratelimit.exceeded";
7
+ };
8
+ export interface RateLimitKeyContext {
9
+ request: Request;
10
+ server: Server<unknown> | null;
11
+ ip: string;
12
+ }
13
+ export interface RateLimitMacroOptions {
14
+ limit: number;
15
+ window: number;
16
+ keyGenerator?: (context: RateLimitKeyContext) => string;
17
+ }
18
+ export declare const extractClientIp: (request: Request, server: Server<unknown> | null) => string;
19
+ export declare const rateLimitPlugin: (store?: KvStore) => Elysia<"rateLimitPlugin", {
20
+ decorator: {};
21
+ derive: {};
22
+ resolve: {};
23
+ store: {};
24
+ }, {
25
+ typebox: {
26
+ RateLimitError: (typeof rateLimitContract)[429];
27
+ };
28
+ error: {};
29
+ }, {
30
+ macro: Partial<{
31
+ readonly rateLimit: RateLimitMacroOptions;
32
+ }>;
33
+ macroFn: {
34
+ rateLimit: (options: RateLimitMacroOptions) => {
35
+ response: {
36
+ 429: "RateLimitError";
37
+ };
38
+ transform: ({ set, request, server }: {
39
+ set: {
40
+ headers: HTTPHeaders;
41
+ status?: number | keyof StatusMap;
42
+ };
43
+ request: Request;
44
+ server: Server<unknown> | null;
45
+ }) => Promise<void>;
46
+ };
47
+ };
48
+ parser: {};
49
+ response: {};
50
+ schema: {};
51
+ standaloneSchema: {};
52
+ }>;
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@clov-std/elysia-ratelimit",
3
+ "version": "1.2.1",
4
+ "description": "Rate limiting plugin for Elysia framework.",
5
+ "keywords": [
6
+ "bun",
7
+ "clov",
8
+ "elysia",
9
+ "macro",
10
+ "open-source",
11
+ "plugin",
12
+ "ratelimit",
13
+ "typescript"
14
+ ],
15
+ "license": "MIT",
16
+ "author": "Clov",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/ClovLabs/std",
20
+ "directory": "packages/elysia-ratelimit"
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "type": "module",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ }
31
+ },
32
+ "scripts": {
33
+ "build": "bun builder.ts",
34
+ "docs": "bunx typedoc --tsconfig tsconfig.build.json",
35
+ "fmt:check": "oxfmt --check",
36
+ "fmt": "oxfmt",
37
+ "lint:fix": "oxlint --type-aware --type-check --fix ./src",
38
+ "lint:github": "oxlint --type-aware --type-check --format=github ./src",
39
+ "lint": "oxlint --type-aware --type-check ./src",
40
+ "test": "bun test --pass-with-no-tests --coverage"
41
+ },
42
+ "dependencies": {
43
+ "@clov-std/error": "workspace:^",
44
+ "@clov-std/kv-store": "workspace:^",
45
+ "elysia": "^1.4.29"
46
+ },
47
+ "devDependencies": {
48
+ "@types/bun": "catalog:base",
49
+ "oxfmt": "catalog:base",
50
+ "oxlint": "catalog:base",
51
+ "oxlint-tsgolint": "catalog:base",
52
+ "typescript": "catalog:base"
53
+ },
54
+ "peerDependencies": {
55
+ "@clov-std/error": "workspace:^",
56
+ "@clov-std/kv-store": "workspace:^",
57
+ "elysia": "^1.4.29"
58
+ }
59
+ }