@sigil-dev/plugin-ratelimit 0.0.0-stage → 0.9.18

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,3 +1,37 @@
1
- # Temporary Holding Version
1
+ # @sigil-dev/plugin-ratelimit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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 ADDED
@@ -0,0 +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";
package/memory.ts ADDED
@@ -0,0 +1,57 @@
1
+ import type { RateLimitBackend } from "./index";
2
+
3
+ interface Entry {
4
+ count: number;
5
+ resetAt: number;
6
+ }
7
+
8
+ /**
9
+ * In-memory rate limit store.
10
+ *
11
+ * WARNING: Not safe for multi-worker deployments (`sigil start --scale`).
12
+ * Each worker has its own memory — counters do not share across processes.
13
+ * Use the Redis backend in production with multiple workers.
14
+ */
15
+ export class MemoryStore implements RateLimitBackend {
16
+ private store = new Map<string, Entry>();
17
+ private pruneInterval: ReturnType<typeof setInterval>;
18
+
19
+ constructor() {
20
+ // prune expired entries every 60s to prevent unbounded memory growth
21
+ this.pruneInterval = setInterval(() => {
22
+ const now = Date.now();
23
+ for (const [key, entry] of this.store) {
24
+ if (entry.resetAt <= now) this.store.delete(key);
25
+ }
26
+ }, 60_000);
27
+ // don't block process exit
28
+ if (typeof this.pruneInterval.unref === "function") {
29
+ this.pruneInterval.unref();
30
+ }
31
+ }
32
+
33
+ async increment(
34
+ key: string,
35
+ windowMs: number,
36
+ ): Promise<{ count: number; resetAt: number }> {
37
+ const now = Date.now();
38
+ const entry = this.store.get(key);
39
+
40
+ if (!entry || entry.resetAt <= now) {
41
+ const resetAt = now + windowMs;
42
+ this.store.set(key, { count: 1, resetAt });
43
+ return { count: 1, resetAt };
44
+ }
45
+
46
+ entry.count++;
47
+ return { count: entry.count, resetAt: entry.resetAt };
48
+ }
49
+
50
+ async reset(key: string): Promise<void> {
51
+ this.store.delete(key);
52
+ }
53
+
54
+ async close(): Promise<void> {
55
+ clearInterval(this.pruneInterval);
56
+ }
57
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@sigil-dev/plugin-ratelimit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Per-client request rate limits for Grimoire, in memory or Redis",
4
+ "license": "MIT",
5
+ "homepage": "https://sigil.cane1712.dev/docs/reference/plugins",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://git.cane1712.dev/sigil/sigil.git",
9
+ "directory": "packages/plugin-ratelimit"
10
+ },
11
+ "module": "index.ts",
12
+ "type": "module",
13
+ "files": [
14
+ "index.ts",
15
+ "memory.ts",
16
+ "redis.ts",
17
+ "README.md"
18
+ ],
19
+ "private": false,
20
+ "dependencies": {
21
+ "@sigil-dev/grimoire": "0.9.18"
22
+ },
23
+ "devDependencies": {
24
+ "@types/bun": "latest"
25
+ },
26
+ "peerDependencies": {
27
+ "typescript": "^5"
28
+ },
29
+ "version": "0.9.18"
30
+ }
package/redis.ts ADDED
@@ -0,0 +1,58 @@
1
+ import type { RateLimitBackend } from "./index";
2
+
3
+ export interface RedisBackendOptions {
4
+ url?: string; // default: "redis://localhost:6379"
5
+ keyPrefix?: string; // default: "rl:"
6
+ }
7
+
8
+ /**
9
+ * Redis-backed rate limit store using Bun's native Redis client.
10
+ * Safe for multi-worker deployments — counters are shared across all processes.
11
+ *
12
+ * Uses a fixed window algorithm with INCR + PEXPIRE.
13
+ * The increment + expiry are not fully atomic — under extreme concurrency
14
+ * the PEXPIRE may be missed if the process crashes between the two calls.
15
+ * For most applications this is acceptable. Use a Lua script if you need
16
+ * strict atomicity.
17
+ */
18
+ export class RedisStore implements RateLimitBackend {
19
+ private redis: import("bun").RedisClient;
20
+ private keyPrefix: string;
21
+
22
+ constructor(opts: RedisBackendOptions = {}) {
23
+ const { url = "redis://localhost:6379", keyPrefix = "rl:" } = opts;
24
+ this.redis = new (require("bun").Redis)(url);
25
+ this.keyPrefix = keyPrefix;
26
+ }
27
+
28
+ async increment(
29
+ key: string,
30
+ windowMs: number,
31
+ ): Promise<{ count: number; resetAt: number }> {
32
+ const redisKey = `${this.keyPrefix}${key}`;
33
+
34
+ const count = await this.redis.incr(redisKey);
35
+
36
+ if (count === 1) {
37
+ // first request in this window — set expiry
38
+ await this.redis.pexpire(redisKey, windowMs);
39
+ }
40
+
41
+ const ttl = await this.redis.pttl(redisKey);
42
+ const resetAt = Date.now() + (ttl > 0 ? ttl : windowMs);
43
+
44
+ return { count, resetAt };
45
+ }
46
+
47
+ async reset(key: string): Promise<void> {
48
+ await this.redis.del(`${this.keyPrefix}${key}`);
49
+ }
50
+
51
+ async close(): Promise<void> {
52
+ this.redis.close();
53
+ }
54
+ }
55
+
56
+ export function redis(opts: RedisBackendOptions = {}): RedisStore {
57
+ return new RedisStore(opts);
58
+ }