@sigil-dev/plugin-ratelimit 0.9.20 → 0.9.22

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.
Files changed (3) hide show
  1. package/README.md +37 -37
  2. package/index.ts +214 -214
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,37 +1,37 @@
1
- # @sigil-dev/plugin-ratelimit
2
-
3
- Per-visitor request limits for Grimoire, in memory or in Redis.
4
-
5
- ```ts
6
- // sigil.config.ts
7
- import { rateLimit, redis } from "@sigil-dev/plugin-ratelimit";
8
-
9
- export default defineConfig({
10
- plugins: [
11
- rateLimit({
12
- max: 100, // per minute, per visitor
13
- routes: {
14
- // five sign-in attempts a minute; visiting the page doesn't count
15
- "/login": { max: 5, methods: ["POST"] },
16
- },
17
- backend: redis({ url: Bun.env.REDIS_URL }), // "memory" (the default) is per worker
18
- }),
19
- ],
20
- });
21
- ```
22
-
23
- A request over its limit gets a `429` with `Retry-After`; every response carries `X-RateLimit-Limit`, `-Remaining` and `-Reset`.
24
-
25
- - **Each route limit has its own allowance.** Browsing the site doesn't use up the five sign-in attempts, and sign-in attempts don't use up the site-wide 100.
26
- - **A route covers whole path segments**: `/api` limits `/api` and `/api/users`, not `/apiary`. The most specific route wins.
27
- - **The visitor is found the way Grimoire finds them** (`clientAddress`): behind a reverse proxy on the same machine or private network, the address the proxy reports; otherwise the connection's own, so a visitor can't dodge the limit by sending a made-up `X-Forwarded-For`. Under `sigil start` the coordinator passes the address to the workers.
28
-
29
- | Option | Default | |
30
- | --- | --- | --- |
31
- | `max` | `100` | Requests per window |
32
- | `windowMs` | `60_000` | Window length |
33
- | `routes` | none | `{ "/path": { max, windowMs, methods } }` |
34
- | `keyBy` | the visitor's IP | `(req, server) => string` |
35
- | `skip` | none | `(req) => boolean`, for health checks and trusted callers |
36
- | `backend` | `"memory"` | `"memory"` or `redis({ url, keyPrefix })` |
37
- | `message` | `Too Many Requests` | The 429 body |
1
+ # @sigil-dev/plugin-ratelimit
2
+
3
+ Per-visitor request limits for Grimoire, in memory or in Redis.
4
+
5
+ ```ts
6
+ // sigil.config.ts
7
+ import { rateLimit, redis } from "@sigil-dev/plugin-ratelimit";
8
+
9
+ export default defineConfig({
10
+ plugins: [
11
+ rateLimit({
12
+ max: 100, // per minute, per visitor
13
+ routes: {
14
+ // five sign-in attempts a minute; visiting the page doesn't count
15
+ "/login": { max: 5, methods: ["POST"] },
16
+ },
17
+ backend: redis({ url: Bun.env.REDIS_URL }), // "memory" (the default) is per worker
18
+ }),
19
+ ],
20
+ });
21
+ ```
22
+
23
+ A request over its limit gets a `429` with `Retry-After`; every response carries `X-RateLimit-Limit`, `-Remaining` and `-Reset`.
24
+
25
+ - **Each route limit has its own allowance.** Browsing the site doesn't use up the five sign-in attempts, and sign-in attempts don't use up the site-wide 100.
26
+ - **A route covers whole path segments**: `/api` limits `/api` and `/api/users`, not `/apiary`. The most specific route wins.
27
+ - **The visitor is found the way Grimoire finds them** (`clientAddress`): behind a reverse proxy on the same machine or private network, the address the proxy reports; otherwise the connection's own, so a visitor can't dodge the limit by sending a made-up `X-Forwarded-For`. Under `sigil start` the coordinator passes the address to the workers.
28
+
29
+ | Option | Default | |
30
+ | --- | --- | --- |
31
+ | `max` | `100` | Requests per window |
32
+ | `windowMs` | `60_000` | Window length |
33
+ | `routes` | none | `{ "/path": { max, windowMs, methods } }` |
34
+ | `keyBy` | the visitor's IP | `(req, server) => string` |
35
+ | `skip` | none | `(req) => boolean`, for health checks and trusted callers |
36
+ | `backend` | `"memory"` | `"memory"` or `redis({ url, keyPrefix })` |
37
+ | `message` | `Too Many Requests` | The 429 body |
package/index.ts CHANGED
@@ -1,214 +1,214 @@
1
- import { clientAddress, type GrimoirePlugin } from "@sigil-dev/grimoire";
2
- import type { Server } from "bun";
3
- import { MemoryStore } from "./memory";
4
-
5
- export interface RateLimitBackend {
6
- increment(
7
- key: string,
8
- windowMs: number,
9
- ): Promise<{ count: number; resetAt: number }>;
10
- reset(key: string): Promise<void>;
11
- close?(): Promise<void>;
12
- }
13
-
14
- export interface RouteLimit {
15
- /** Max requests per window for this route. Overrides global max. */
16
- max?: number;
17
- /** Window duration in ms for this route. Overrides global windowMs. */
18
- windowMs?: number;
19
- /**
20
- * Only these methods count against this limit: `["POST"]` throttles sign-in
21
- * attempts without counting visits to the login page. Other methods fall
22
- * back to the global limit.
23
- */
24
- methods?: string[];
25
- }
26
-
27
- export interface RateLimitOptions {
28
- /**
29
- * Time window in milliseconds.
30
- * @default 60_000 (1 minute)
31
- */
32
- windowMs?: number;
33
-
34
- /**
35
- * Maximum number of requests per window per key.
36
- * @default 100
37
- */
38
- max?: number;
39
-
40
- /**
41
- * Who a request counts against. Defaults to the visitor's IP address, as
42
- * Grimoire works it out: behind a reverse proxy on the same machine or
43
- * network, the address the proxy reports; otherwise the connection's.
44
- */
45
- keyBy?: (req: Request, server: Server<unknown>) => string | Promise<string>;
46
-
47
- /**
48
- * Storage backend.
49
- * - "memory" — in-process Map. Fast, zero deps. NOT safe for multi-worker.
50
- * - redis(opts) — Bun-native Redis client. Safe for multi-worker.
51
- * @default "memory"
52
- */
53
- backend?: "memory" | RateLimitBackend;
54
-
55
- /**
56
- * Per-route overrides. Keys are exact URL pathnames.
57
- * @example
58
- * routes: {
59
- * "/api/auth/login": { max: 5 },
60
- * "/api/upload": { max: 10, windowMs: 3_600_000 },
61
- * }
62
- */
63
- routes?: Record<string, RouteLimit>;
64
-
65
- /**
66
- * Skip rate limiting for matching requests entirely.
67
- * Useful for internal health checks, trusted IPs, etc.
68
- */
69
- skip?: (req: Request) => boolean | Promise<boolean>;
70
-
71
- /**
72
- * Response body for 429 responses.
73
- * @default "Too Many Requests"
74
- */
75
- message?: string;
76
- }
77
-
78
- const defaultKeyBy = (req: Request, server: Server<unknown>): string =>
79
- clientAddress(req, server);
80
-
81
- /** `/api` covers `/api` and `/api/users`, not `/apiary`. */
82
- const covers = (prefix: string, pathname: string) =>
83
- pathname === prefix ||
84
- pathname.startsWith(prefix.endsWith("/") ? prefix : `${prefix}/`);
85
-
86
- /**
87
- * The limit a request falls under, and the bucket it counts in. Each route
88
- * limit has its own bucket: a tight limit on /login is not spent by visits to
89
- * other pages, and visits to /login do not eat into the global allowance.
90
- */
91
- function resolveRouteLimit(
92
- pathname: string,
93
- method: string,
94
- routes: Record<string, RouteLimit> | undefined,
95
- globalMax: number,
96
- globalWindowMs: number,
97
- ): { max: number; windowMs: number; bucket: string } {
98
- const applies = (limit: RouteLimit) =>
99
- !limit.methods || limit.methods.some((m) => m.toUpperCase() === method);
100
-
101
- let best: [string, RouteLimit] | undefined;
102
- for (const entry of Object.entries(routes ?? {})) {
103
- const [pattern, limit] = entry;
104
- if (!covers(pattern, pathname) || !applies(limit)) continue;
105
- // exact beats prefix; among prefixes the longest wins
106
- if (
107
- !best ||
108
- pattern === pathname ||
109
- (best[0] !== pathname && pattern.length > best[0].length)
110
- ) {
111
- best = entry;
112
- }
113
- }
114
- if (!best) return { max: globalMax, windowMs: globalWindowMs, bucket: "*" };
115
- const [pattern, limit] = best;
116
- return {
117
- max: limit.max ?? globalMax,
118
- windowMs: limit.windowMs ?? globalWindowMs,
119
- bucket: pattern,
120
- };
121
- }
122
-
123
- export function rateLimit(opts: RateLimitOptions = {}): GrimoirePlugin {
124
- const {
125
- windowMs: globalWindowMs = 60_000,
126
- max: globalMax = 100,
127
- keyBy = defaultKeyBy,
128
- backend = "memory",
129
- routes,
130
- skip,
131
- message = "Too Many Requests",
132
- } = opts;
133
-
134
- const store: RateLimitBackend =
135
- backend === "memory" ? new MemoryStore() : backend;
136
-
137
- let server: Server<unknown> | null = null;
138
-
139
- return {
140
- name: "grimoire-ratelimit",
141
-
142
- onStart(s) {
143
- server = s;
144
- },
145
-
146
- onStop() {
147
- return Promise.resolve(store.close?.());
148
- },
149
-
150
- async onRequest(req, next) {
151
- // skip websocket upgrades
152
- if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
153
- return next();
154
- }
155
-
156
- if (skip && (await skip(req))) {
157
- return next();
158
- }
159
-
160
- if (!server) {
161
- // server not ready yet — should never happen in practice
162
- return next();
163
- }
164
-
165
- const url = new URL(req.url);
166
- const { max, windowMs, bucket } = resolveRouteLimit(
167
- url.pathname,
168
- req.method,
169
- routes,
170
- globalMax,
171
- globalWindowMs,
172
- );
173
-
174
- const key = `${await keyBy(req, server)}|${bucket}`;
175
- const { count, resetAt } = await store.increment(key, windowMs);
176
-
177
- const remaining = Math.max(0, max - count);
178
- const retryAfter = Math.ceil((resetAt - Date.now()) / 1000);
179
-
180
- const headers: Record<string, string> = {
181
- "X-RateLimit-Limit": String(max),
182
- "X-RateLimit-Remaining": String(remaining),
183
- "X-RateLimit-Reset": String(Math.ceil(resetAt / 1000)),
184
- };
185
-
186
- if (count > max) {
187
- return new Response(message, {
188
- status: 429,
189
- headers: {
190
- ...headers,
191
- "Retry-After": String(retryAfter),
192
- "Content-Type": "text/plain",
193
- },
194
- });
195
- }
196
-
197
- const response = await next();
198
-
199
- // attach headers to successful responses too — clients can track their usage
200
- const patched = new Response(response.body, {
201
- status: response.status,
202
- statusText: response.statusText,
203
- headers: response.headers,
204
- });
205
- for (const [k, v] of Object.entries(headers)) {
206
- patched.headers.set(k, v);
207
- }
208
-
209
- return patched;
210
- },
211
- };
212
- }
213
-
214
- export { redis } from "./redis";
1
+ import { clientAddress, type GrimoirePlugin } from "@sigil-dev/grimoire";
2
+ import type { Server } from "bun";
3
+ import { MemoryStore } from "./memory";
4
+
5
+ export interface RateLimitBackend {
6
+ increment(
7
+ key: string,
8
+ windowMs: number,
9
+ ): Promise<{ count: number; resetAt: number }>;
10
+ reset(key: string): Promise<void>;
11
+ close?(): Promise<void>;
12
+ }
13
+
14
+ export interface RouteLimit {
15
+ /** Max requests per window for this route. Overrides global max. */
16
+ max?: number;
17
+ /** Window duration in ms for this route. Overrides global windowMs. */
18
+ windowMs?: number;
19
+ /**
20
+ * Only these methods count against this limit: `["POST"]` throttles sign-in
21
+ * attempts without counting visits to the login page. Other methods fall
22
+ * back to the global limit.
23
+ */
24
+ methods?: string[];
25
+ }
26
+
27
+ export interface RateLimitOptions {
28
+ /**
29
+ * Time window in milliseconds.
30
+ * @default 60_000 (1 minute)
31
+ */
32
+ windowMs?: number;
33
+
34
+ /**
35
+ * Maximum number of requests per window per key.
36
+ * @default 100
37
+ */
38
+ max?: number;
39
+
40
+ /**
41
+ * Who a request counts against. Defaults to the visitor's IP address, as
42
+ * Grimoire works it out: behind a reverse proxy on the same machine or
43
+ * network, the address the proxy reports; otherwise the connection's.
44
+ */
45
+ keyBy?: (req: Request, server: Server<unknown>) => string | Promise<string>;
46
+
47
+ /**
48
+ * Storage backend.
49
+ * - "memory" — in-process Map. Fast, zero deps. NOT safe for multi-worker.
50
+ * - redis(opts) — Bun-native Redis client. Safe for multi-worker.
51
+ * @default "memory"
52
+ */
53
+ backend?: "memory" | RateLimitBackend;
54
+
55
+ /**
56
+ * Per-route overrides. Keys are exact URL pathnames.
57
+ * @example
58
+ * routes: {
59
+ * "/api/auth/login": { max: 5 },
60
+ * "/api/upload": { max: 10, windowMs: 3_600_000 },
61
+ * }
62
+ */
63
+ routes?: Record<string, RouteLimit>;
64
+
65
+ /**
66
+ * Skip rate limiting for matching requests entirely.
67
+ * Useful for internal health checks, trusted IPs, etc.
68
+ */
69
+ skip?: (req: Request) => boolean | Promise<boolean>;
70
+
71
+ /**
72
+ * Response body for 429 responses.
73
+ * @default "Too Many Requests"
74
+ */
75
+ message?: string;
76
+ }
77
+
78
+ const defaultKeyBy = (req: Request, server: Server<unknown>): string =>
79
+ clientAddress(req, server);
80
+
81
+ /** `/api` covers `/api` and `/api/users`, not `/apiary`. */
82
+ const covers = (prefix: string, pathname: string) =>
83
+ pathname === prefix ||
84
+ pathname.startsWith(prefix.endsWith("/") ? prefix : `${prefix}/`);
85
+
86
+ /**
87
+ * The limit a request falls under, and the bucket it counts in. Each route
88
+ * limit has its own bucket: a tight limit on /login is not spent by visits to
89
+ * other pages, and visits to /login do not eat into the global allowance.
90
+ */
91
+ function resolveRouteLimit(
92
+ pathname: string,
93
+ method: string,
94
+ routes: Record<string, RouteLimit> | undefined,
95
+ globalMax: number,
96
+ globalWindowMs: number,
97
+ ): { max: number; windowMs: number; bucket: string } {
98
+ const applies = (limit: RouteLimit) =>
99
+ !limit.methods || limit.methods.some((m) => m.toUpperCase() === method);
100
+
101
+ let best: [string, RouteLimit] | undefined;
102
+ for (const entry of Object.entries(routes ?? {})) {
103
+ const [pattern, limit] = entry;
104
+ if (!covers(pattern, pathname) || !applies(limit)) continue;
105
+ // exact beats prefix; among prefixes the longest wins
106
+ if (
107
+ !best ||
108
+ pattern === pathname ||
109
+ (best[0] !== pathname && pattern.length > best[0].length)
110
+ ) {
111
+ best = entry;
112
+ }
113
+ }
114
+ if (!best) return { max: globalMax, windowMs: globalWindowMs, bucket: "*" };
115
+ const [pattern, limit] = best;
116
+ return {
117
+ max: limit.max ?? globalMax,
118
+ windowMs: limit.windowMs ?? globalWindowMs,
119
+ bucket: pattern,
120
+ };
121
+ }
122
+
123
+ export function rateLimit(opts: RateLimitOptions = {}): GrimoirePlugin {
124
+ const {
125
+ windowMs: globalWindowMs = 60_000,
126
+ max: globalMax = 100,
127
+ keyBy = defaultKeyBy,
128
+ backend = "memory",
129
+ routes,
130
+ skip,
131
+ message = "Too Many Requests",
132
+ } = opts;
133
+
134
+ const store: RateLimitBackend =
135
+ backend === "memory" ? new MemoryStore() : backend;
136
+
137
+ let server: Server<unknown> | null = null;
138
+
139
+ return {
140
+ name: "grimoire-ratelimit",
141
+
142
+ onStart(s) {
143
+ server = s;
144
+ },
145
+
146
+ onStop() {
147
+ return Promise.resolve(store.close?.());
148
+ },
149
+
150
+ async onRequest(req, next) {
151
+ // skip websocket upgrades
152
+ if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
153
+ return next();
154
+ }
155
+
156
+ if (skip && (await skip(req))) {
157
+ return next();
158
+ }
159
+
160
+ if (!server) {
161
+ // server not ready yet — should never happen in practice
162
+ return next();
163
+ }
164
+
165
+ const url = new URL(req.url);
166
+ const { max, windowMs, bucket } = resolveRouteLimit(
167
+ url.pathname,
168
+ req.method,
169
+ routes,
170
+ globalMax,
171
+ globalWindowMs,
172
+ );
173
+
174
+ const key = `${await keyBy(req, server)}|${bucket}`;
175
+ const { count, resetAt } = await store.increment(key, windowMs);
176
+
177
+ const remaining = Math.max(0, max - count);
178
+ const retryAfter = Math.ceil((resetAt - Date.now()) / 1000);
179
+
180
+ const headers: Record<string, string> = {
181
+ "X-RateLimit-Limit": String(max),
182
+ "X-RateLimit-Remaining": String(remaining),
183
+ "X-RateLimit-Reset": String(Math.ceil(resetAt / 1000)),
184
+ };
185
+
186
+ if (count > max) {
187
+ return new Response(message, {
188
+ status: 429,
189
+ headers: {
190
+ ...headers,
191
+ "Retry-After": String(retryAfter),
192
+ "Content-Type": "text/plain",
193
+ },
194
+ });
195
+ }
196
+
197
+ const response = await next();
198
+
199
+ // attach headers to successful responses too — clients can track their usage
200
+ const patched = new Response(response.body, {
201
+ status: response.status,
202
+ statusText: response.statusText,
203
+ headers: response.headers,
204
+ });
205
+ for (const [k, v] of Object.entries(headers)) {
206
+ patched.headers.set(k, v);
207
+ }
208
+
209
+ return patched;
210
+ },
211
+ };
212
+ }
213
+
214
+ export { redis } from "./redis";
package/package.json CHANGED
@@ -18,7 +18,7 @@
18
18
  ],
19
19
  "private": false,
20
20
  "dependencies": {
21
- "@sigil-dev/grimoire": "0.9.20"
21
+ "@sigil-dev/grimoire": "0.9.22"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@types/bun": "latest"
@@ -26,5 +26,5 @@
26
26
  "peerDependencies": {
27
27
  "typescript": "^5"
28
28
  },
29
- "version": "0.9.20"
29
+ "version": "0.9.22"
30
30
  }