@jellyfungus/hono-rate-limiter 0.3.0 → 0.4.0
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 +51 -0
- package/dist/index.cjs +128 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -1
- package/dist/index.d.ts +26 -1
- package/dist/index.js +126 -16
- package/dist/index.js.map +1 -1
- package/dist/websocket.cjs.map +1 -1
- package/dist/websocket.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -123,6 +123,8 @@ app.use(
|
|
|
123
123
|
|
|
124
124
|
For Cloudflare Workers with KV:
|
|
125
125
|
|
|
126
|
+
> **Warning:** Cloudflare KV is eventually consistent and does not support atomic increment operations. Under high concurrency, rate limits may be slightly exceeded. For strict rate limiting on Cloudflare, use [Durable Objects](https://developers.cloudflare.com/durable-objects/) or the native [Rate Limiting binding](#cloudflare-rate-limiting-binding) below.
|
|
127
|
+
|
|
126
128
|
```ts
|
|
127
129
|
import { rateLimiter } from "@jellyfungus/hono-rate-limiter";
|
|
128
130
|
import { CloudflareKVStore } from "@jellyfungus/hono-rate-limiter/store/cloudflare-kv";
|
|
@@ -373,6 +375,55 @@ Use `headers: false` to disable all rate limit headers.
|
|
|
373
375
|
|
|
374
376
|
When a request is rate limited (429 response), the `Retry-After` header is always included with the number of seconds until the client can retry.
|
|
375
377
|
|
|
378
|
+
## Security Considerations
|
|
379
|
+
|
|
380
|
+
### IP Header Spoofing
|
|
381
|
+
|
|
382
|
+
The default key generator uses request headers (`X-Forwarded-For`, `X-Real-IP`, `CF-Connecting-IP`) to identify clients. **These headers can be spoofed by malicious clients** if your application is not behind a trusted reverse proxy.
|
|
383
|
+
|
|
384
|
+
**Only trust these headers when your app is behind a trusted proxy** (nginx, Cloudflare, AWS ALB, etc.) that overwrites them.
|
|
385
|
+
|
|
386
|
+
For untrusted environments or additional security, use authenticated identifiers:
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
app.use(
|
|
390
|
+
rateLimiter({
|
|
391
|
+
keyGenerator: (c) => {
|
|
392
|
+
// Use authenticated user ID instead of IP
|
|
393
|
+
const user = c.get("user");
|
|
394
|
+
return user?.id ?? "anonymous";
|
|
395
|
+
},
|
|
396
|
+
}),
|
|
397
|
+
);
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
### Error Handling
|
|
401
|
+
|
|
402
|
+
By default, the rate limiter uses a "fail-open" strategy: if the store (Redis, KV, etc.) is unavailable, requests are allowed through. This prioritizes availability over strict rate limiting.
|
|
403
|
+
|
|
404
|
+
For stricter security, use "fail-closed":
|
|
405
|
+
|
|
406
|
+
```ts
|
|
407
|
+
app.use(
|
|
408
|
+
rateLimiter({
|
|
409
|
+
onStoreError: "deny", // Block requests when store fails
|
|
410
|
+
}),
|
|
411
|
+
);
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
Or use a custom handler:
|
|
415
|
+
|
|
416
|
+
```ts
|
|
417
|
+
app.use(
|
|
418
|
+
rateLimiter({
|
|
419
|
+
onStoreError: (error, c) => {
|
|
420
|
+
console.error("Rate limiter error:", error);
|
|
421
|
+
return false; // false = deny, true = allow
|
|
422
|
+
},
|
|
423
|
+
}),
|
|
424
|
+
);
|
|
425
|
+
```
|
|
426
|
+
|
|
376
427
|
## License
|
|
377
428
|
|
|
378
429
|
MIT
|
package/dist/index.cjs
CHANGED
|
@@ -23,7 +23,8 @@ __export(index_exports, {
|
|
|
23
23
|
MemoryStore: () => MemoryStore,
|
|
24
24
|
cloudflareRateLimiter: () => cloudflareRateLimiter,
|
|
25
25
|
getClientIP: () => getClientIP,
|
|
26
|
-
rateLimiter: () => rateLimiter
|
|
26
|
+
rateLimiter: () => rateLimiter,
|
|
27
|
+
shutdownDefaultStore: () => shutdownDefaultStore
|
|
27
28
|
});
|
|
28
29
|
module.exports = __toCommonJS(index_exports);
|
|
29
30
|
var MemoryStore = class {
|
|
@@ -82,23 +83,30 @@ var MemoryStore = class {
|
|
|
82
83
|
}
|
|
83
84
|
};
|
|
84
85
|
var defaultStore;
|
|
86
|
+
function shutdownDefaultStore() {
|
|
87
|
+
if (defaultStore) {
|
|
88
|
+
defaultStore.shutdown();
|
|
89
|
+
defaultStore = void 0;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
85
92
|
function setHeaders(c, info, format, windowMs, identifier, quotaUnit) {
|
|
86
93
|
if (format === false) {
|
|
87
94
|
return;
|
|
88
95
|
}
|
|
89
96
|
const windowSeconds = Math.ceil(windowMs / 1e3);
|
|
90
97
|
const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1e3));
|
|
98
|
+
const safeId = sanitizeIdentifier(identifier);
|
|
91
99
|
switch (format) {
|
|
92
100
|
case "standard":
|
|
93
101
|
{
|
|
94
|
-
let policy = `"${
|
|
102
|
+
let policy = `"${safeId}";q=${info.limit};w=${windowSeconds}`;
|
|
95
103
|
if (quotaUnit !== "requests") {
|
|
96
104
|
policy += `;qu="${quotaUnit}"`;
|
|
97
105
|
}
|
|
98
106
|
c.header("RateLimit-Policy", policy);
|
|
99
107
|
c.header(
|
|
100
108
|
"RateLimit",
|
|
101
|
-
`"${
|
|
109
|
+
`"${safeId}";r=${info.remaining};t=${resetSeconds}`
|
|
102
110
|
);
|
|
103
111
|
}
|
|
104
112
|
break;
|
|
@@ -123,6 +131,16 @@ function setHeaders(c, info, format, windowMs, identifier, quotaUnit) {
|
|
|
123
131
|
break;
|
|
124
132
|
}
|
|
125
133
|
}
|
|
134
|
+
function sanitizeIdentifier(id) {
|
|
135
|
+
if (!id || typeof id !== "string") {
|
|
136
|
+
return "default";
|
|
137
|
+
}
|
|
138
|
+
const sanitized = id.replace(/[^a-zA-Z0-9_\-.:*/]/g, "-");
|
|
139
|
+
if (!sanitized || !/^[a-zA-Z]/.test(sanitized)) {
|
|
140
|
+
return "default";
|
|
141
|
+
}
|
|
142
|
+
return sanitized;
|
|
143
|
+
}
|
|
126
144
|
function getClientIP(c) {
|
|
127
145
|
const cfIP = c.req.header("cf-connecting-ip");
|
|
128
146
|
if (cfIP) {
|
|
@@ -138,14 +156,59 @@ function getClientIP(c) {
|
|
|
138
156
|
}
|
|
139
157
|
return "unknown";
|
|
140
158
|
}
|
|
141
|
-
function
|
|
142
|
-
const
|
|
159
|
+
function buildRateLimitHeaders(info, format, windowMs, identifier, quotaUnit) {
|
|
160
|
+
const headers = {
|
|
161
|
+
"Content-Type": "text/plain",
|
|
162
|
+
"Retry-After": String(
|
|
163
|
+
Math.max(0, Math.ceil((info.reset - Date.now()) / 1e3))
|
|
164
|
+
)
|
|
165
|
+
};
|
|
166
|
+
if (format === false) {
|
|
167
|
+
return headers;
|
|
168
|
+
}
|
|
169
|
+
const windowSeconds = Math.ceil(windowMs / 1e3);
|
|
170
|
+
const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1e3));
|
|
171
|
+
const safeId = sanitizeIdentifier(identifier);
|
|
172
|
+
switch (format) {
|
|
173
|
+
case "standard": {
|
|
174
|
+
let policy = `"${safeId}";q=${info.limit};w=${windowSeconds}`;
|
|
175
|
+
if (quotaUnit !== "requests") {
|
|
176
|
+
policy += `;qu="${quotaUnit}"`;
|
|
177
|
+
}
|
|
178
|
+
headers["RateLimit-Policy"] = policy;
|
|
179
|
+
headers["RateLimit"] = `"${safeId}";r=${info.remaining};t=${resetSeconds}`;
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
case "draft-7":
|
|
183
|
+
headers["RateLimit-Policy"] = `${info.limit};w=${windowSeconds}`;
|
|
184
|
+
headers["RateLimit"] = `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`;
|
|
185
|
+
break;
|
|
186
|
+
case "draft-6":
|
|
187
|
+
headers["RateLimit-Policy"] = `${info.limit};w=${windowSeconds}`;
|
|
188
|
+
headers["RateLimit-Limit"] = String(info.limit);
|
|
189
|
+
headers["RateLimit-Remaining"] = String(info.remaining);
|
|
190
|
+
headers["RateLimit-Reset"] = String(resetSeconds);
|
|
191
|
+
break;
|
|
192
|
+
case "legacy":
|
|
193
|
+
default:
|
|
194
|
+
headers["X-RateLimit-Limit"] = String(info.limit);
|
|
195
|
+
headers["X-RateLimit-Remaining"] = String(info.remaining);
|
|
196
|
+
headers["X-RateLimit-Reset"] = String(Math.ceil(info.reset / 1e3));
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
return headers;
|
|
200
|
+
}
|
|
201
|
+
function createDefaultResponse(info, format, windowMs, identifier, quotaUnit) {
|
|
202
|
+
const headers = buildRateLimitHeaders(
|
|
203
|
+
info,
|
|
204
|
+
format,
|
|
205
|
+
windowMs,
|
|
206
|
+
identifier,
|
|
207
|
+
quotaUnit
|
|
208
|
+
);
|
|
143
209
|
return new Response("Rate limit exceeded", {
|
|
144
210
|
status: 429,
|
|
145
|
-
headers
|
|
146
|
-
"Content-Type": "text/plain",
|
|
147
|
-
"Retry-After": String(retryAfter)
|
|
148
|
-
}
|
|
211
|
+
headers
|
|
149
212
|
});
|
|
150
213
|
}
|
|
151
214
|
async function checkSlidingWindow(store, key, limit, windowMs) {
|
|
@@ -198,14 +261,37 @@ var rateLimiter = (options) => {
|
|
|
198
261
|
skipSuccessfulRequests: false,
|
|
199
262
|
skipFailedRequests: false,
|
|
200
263
|
onRateLimited: void 0,
|
|
264
|
+
onStoreError: "allow",
|
|
201
265
|
...options
|
|
202
266
|
};
|
|
203
267
|
const store = opts.store ?? (defaultStore ??= new MemoryStore());
|
|
204
|
-
let
|
|
268
|
+
let initPromise = null;
|
|
269
|
+
async function handleStoreError(error, c) {
|
|
270
|
+
if (typeof opts.onStoreError === "function") {
|
|
271
|
+
return opts.onStoreError(error, c);
|
|
272
|
+
}
|
|
273
|
+
return opts.onStoreError === "allow";
|
|
274
|
+
}
|
|
205
275
|
return async function rateLimiter2(c, next) {
|
|
206
|
-
if (!
|
|
207
|
-
|
|
208
|
-
|
|
276
|
+
if (!initPromise && store.init) {
|
|
277
|
+
const result = store.init(opts.windowMs);
|
|
278
|
+
initPromise = result instanceof Promise ? result : Promise.resolve();
|
|
279
|
+
}
|
|
280
|
+
if (initPromise) {
|
|
281
|
+
try {
|
|
282
|
+
await initPromise;
|
|
283
|
+
} catch (error) {
|
|
284
|
+
const shouldAllow = await handleStoreError(
|
|
285
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
286
|
+
c
|
|
287
|
+
);
|
|
288
|
+
if (shouldAllow) {
|
|
289
|
+
return next();
|
|
290
|
+
}
|
|
291
|
+
return new Response("Rate limiter initialization failed", {
|
|
292
|
+
status: 500
|
|
293
|
+
});
|
|
294
|
+
}
|
|
209
295
|
}
|
|
210
296
|
if (opts.skip) {
|
|
211
297
|
const shouldSkip = await opts.skip(c);
|
|
@@ -215,7 +301,22 @@ var rateLimiter = (options) => {
|
|
|
215
301
|
}
|
|
216
302
|
const key = await opts.keyGenerator(c);
|
|
217
303
|
const limit = typeof opts.limit === "function" ? await opts.limit(c) : opts.limit;
|
|
218
|
-
|
|
304
|
+
let allowed;
|
|
305
|
+
let info;
|
|
306
|
+
try {
|
|
307
|
+
const result = opts.algorithm === "sliding-window" ? await checkSlidingWindow(store, key, limit, opts.windowMs) : await checkFixedWindow(store, key, limit, opts.windowMs);
|
|
308
|
+
allowed = result.allowed;
|
|
309
|
+
info = result.info;
|
|
310
|
+
} catch (error) {
|
|
311
|
+
const shouldAllow = await handleStoreError(
|
|
312
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
313
|
+
c
|
|
314
|
+
);
|
|
315
|
+
if (shouldAllow) {
|
|
316
|
+
return next();
|
|
317
|
+
}
|
|
318
|
+
return new Response("Rate limiter error", { status: 500 });
|
|
319
|
+
}
|
|
219
320
|
c.set("rateLimit", info);
|
|
220
321
|
c.set("rateLimitStore", {
|
|
221
322
|
getKey: store.get?.bind(store) ?? (() => void 0),
|
|
@@ -236,7 +337,13 @@ var rateLimiter = (options) => {
|
|
|
236
337
|
if (opts.handler) {
|
|
237
338
|
return opts.handler(c, info);
|
|
238
339
|
}
|
|
239
|
-
return createDefaultResponse(
|
|
340
|
+
return createDefaultResponse(
|
|
341
|
+
info,
|
|
342
|
+
opts.headers,
|
|
343
|
+
opts.windowMs,
|
|
344
|
+
opts.identifier,
|
|
345
|
+
opts.quotaUnit
|
|
346
|
+
);
|
|
240
347
|
}
|
|
241
348
|
await next();
|
|
242
349
|
if (opts.skipSuccessfulRequests || opts.skipFailedRequests) {
|
|
@@ -245,7 +352,10 @@ var rateLimiter = (options) => {
|
|
|
245
352
|
if (shouldDecrement && store.decrement) {
|
|
246
353
|
const windowStart = Math.floor(Date.now() / opts.windowMs) * opts.windowMs;
|
|
247
354
|
const windowKey = `${key}:${windowStart}`;
|
|
248
|
-
|
|
355
|
+
try {
|
|
356
|
+
await store.decrement(windowKey);
|
|
357
|
+
} catch {
|
|
358
|
+
}
|
|
249
359
|
}
|
|
250
360
|
}
|
|
251
361
|
};
|
|
@@ -279,6 +389,7 @@ var cloudflareRateLimiter = (options) => {
|
|
|
279
389
|
MemoryStore,
|
|
280
390
|
cloudflareRateLimiter,
|
|
281
391
|
getClientIP,
|
|
282
|
-
rateLimiter
|
|
392
|
+
rateLimiter,
|
|
393
|
+
shutdownDefaultStore
|
|
283
394
|
});
|
|
284
395
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @module\n * Rate Limit Middleware for Hono.\n */\n\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Rate limit information for a single request\n */\nexport type RateLimitInfo = {\n /** Maximum requests allowed in window */\n limit: number;\n /** Remaining requests in current window */\n remaining: number;\n /** Unix timestamp (ms) when window resets */\n reset: number;\n};\n\n/**\n * Result from store increment operation\n */\nexport type StoreResult = {\n /** Current request count in window */\n count: number;\n /** When the window resets (Unix timestamp ms) */\n reset: number;\n};\n\n/**\n * Quota unit for IETF standard headers.\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nexport type QuotaUnit = \"requests\" | \"content-bytes\" | \"concurrent-requests\";\n\n/**\n * Header format options.\n *\n * ## \"legacy\" (default)\n * Common X-RateLimit-* headers used by GitHub, Twitter, and most APIs:\n * - `X-RateLimit-Limit`: max requests in window\n * - `X-RateLimit-Remaining`: remaining requests\n * - `X-RateLimit-Reset`: Unix timestamp (seconds) when window resets\n *\n * ## \"draft-6\"\n * IETF draft-06 format with individual RateLimit-* headers:\n * - `RateLimit-Policy`: policy description (e.g., `100;w=60`)\n * - `RateLimit-Limit`: max requests\n * - `RateLimit-Remaining`: remaining requests\n * - `RateLimit-Reset`: seconds until reset\n *\n * ## \"draft-7\"\n * IETF draft-07 format with combined RateLimit header:\n * - `RateLimit-Policy`: policy description\n * - `RateLimit`: combined (e.g., `limit=100, remaining=50, reset=30`)\n *\n * ## \"standard\"\n * Current IETF draft-08+ format with structured field values (RFC 9651):\n * - `RateLimit-Policy`: `\"name\";q=100;w=60`\n * - `RateLimit`: `\"name\";r=50;t=30`\n *\n * ## false\n * Disable all rate limit headers.\n *\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nexport type HeadersFormat =\n | \"legacy\" // X-RateLimit-* headers (GitHub/Twitter style)\n | \"draft-6\" // IETF draft-06: individual RateLimit-* headers\n | \"draft-7\" // IETF draft-07: combined RateLimit header\n | \"standard\" // IETF draft-08+: structured field format (current)\n | false; // Disable headers\n\n/**\n * Rate limit algorithm\n */\nexport type Algorithm = \"fixed-window\" | \"sliding-window\";\n\n/**\n * Store interface for rate limit state\n */\nexport type RateLimitStore = {\n /**\n * Initialize store. Called once before first use.\n */\n init?: (windowMs: number) => void | Promise<void>;\n\n /**\n * Increment counter for key and return current state.\n */\n increment: (key: string) => StoreResult | Promise<StoreResult>;\n\n /**\n * Decrement counter for key.\n */\n decrement?: (key: string) => void | Promise<void>;\n\n /**\n * Reset a specific key.\n */\n resetKey: (key: string) => void | Promise<void>;\n\n /**\n * Reset all keys.\n */\n resetAll?: () => void | Promise<void>;\n\n /**\n * Get current state for key.\n */\n get?: (\n key: string,\n ) => StoreResult | Promise<StoreResult | undefined> | undefined;\n\n /**\n * Graceful shutdown.\n */\n shutdown?: () => void | Promise<void>;\n};\n\n/**\n * Store access interface exposed in context\n */\nexport type RateLimitStoreAccess = {\n /** Get rate limit info for a key */\n getKey: (\n key: string,\n ) => StoreResult | Promise<StoreResult | undefined> | undefined;\n /** Reset rate limit for a key */\n resetKey: (key: string) => void | Promise<void>;\n};\n\n/**\n * Options for rate limit middleware\n */\nexport type RateLimitOptions<E extends Env = Env> = {\n /**\n * Maximum requests allowed in the time window.\n * @default 60\n */\n limit?: number | ((c: Context<E>) => number | Promise<number>);\n\n /**\n * Time window in milliseconds.\n * @default 60000 (1 minute)\n */\n windowMs?: number;\n\n /**\n * Rate limiting algorithm.\n * @default 'sliding-window'\n */\n algorithm?: Algorithm;\n\n /**\n * Storage backend for rate limit state.\n * @default MemoryStore\n */\n store?: RateLimitStore;\n\n /**\n * Generate unique key for each client.\n * @default IP address from headers\n */\n keyGenerator?: (c: Context<E>) => string | Promise<string>;\n\n /**\n * Handler called when rate limit is exceeded.\n */\n handler?: (\n c: Context<E>,\n info: RateLimitInfo,\n ) => Response | Promise<Response>;\n\n /**\n * HTTP header format to use.\n *\n * - \"legacy\": X-RateLimit-* headers (GitHub/Twitter style, default)\n * - \"draft-6\": IETF draft-06 individual headers\n * - \"draft-7\": IETF draft-07 combined header\n * - \"standard\": IETF draft-08+ structured fields (current spec)\n * - false: Disable headers\n *\n * @default 'legacy'\n */\n headers?: HeadersFormat;\n\n /**\n * Policy identifier for IETF headers (draft-6+).\n * Used in RateLimit and RateLimit-Policy headers.\n * @default 'default'\n */\n identifier?: string;\n\n /**\n * Quota unit for IETF standard headers.\n * Only included in \"standard\" format when not \"requests\".\n * @default 'requests'\n */\n quotaUnit?: QuotaUnit;\n\n /**\n * Skip rate limiting for certain requests.\n */\n skip?: (c: Context<E>) => boolean | Promise<boolean>;\n\n /**\n * Don't count successful (2xx) requests against limit.\n * @default false\n */\n skipSuccessfulRequests?: boolean;\n\n /**\n * Don't count failed (4xx, 5xx) requests against limit.\n * @default false\n */\n skipFailedRequests?: boolean;\n\n /**\n * Callback when a request is rate limited.\n */\n onRateLimited?: (c: Context<E>, info: RateLimitInfo) => void | Promise<void>;\n};\n\n/**\n * Cloudflare Rate Limiting binding interface\n */\nexport type RateLimitBinding = {\n limit: (options: { key: string }) => Promise<{ success: boolean }>;\n};\n\n/**\n * Options for Cloudflare Rate Limiting binding\n */\nexport type CloudflareRateLimitOptions<E extends Env = Env> = {\n /**\n * Cloudflare Rate Limiting binding from env\n */\n binding: RateLimitBinding | ((c: Context<E>) => RateLimitBinding);\n\n /**\n * Generate unique key for each client.\n */\n keyGenerator: (c: Context<E>) => string | Promise<string>;\n\n /**\n * Handler called when rate limit is exceeded.\n */\n handler?: (c: Context<E>) => Response | Promise<Response>;\n\n /**\n * Skip rate limiting for certain requests.\n */\n skip?: (c: Context<E>) => boolean | Promise<boolean>;\n};\n\n// ============================================================================\n// Context Variable Type Extension\n// ============================================================================\n\ndeclare module \"hono\" {\n interface ContextVariableMap {\n rateLimit?: RateLimitInfo;\n rateLimitStore?: RateLimitStoreAccess;\n }\n}\n\n// ============================================================================\n// Memory Store\n// ============================================================================\n\ntype MemoryEntry = {\n count: number;\n reset: number;\n};\n\n/**\n * In-memory store for rate limiting.\n * Suitable for single-instance deployments.\n */\nexport class MemoryStore implements RateLimitStore {\n private entries = new Map<string, MemoryEntry>();\n private windowMs = 60_000;\n private cleanupTimer?: ReturnType<typeof setInterval>;\n\n init(windowMs: number): void {\n this.windowMs = windowMs;\n\n // Cleanup expired entries every minute\n this.cleanupTimer = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of this.entries) {\n if (entry.reset <= now) {\n this.entries.delete(key);\n }\n }\n }, 60_000);\n\n // Don't keep process alive for cleanup\n if (typeof this.cleanupTimer.unref === \"function\") {\n this.cleanupTimer.unref();\n }\n }\n\n increment(key: string): StoreResult {\n const now = Date.now();\n const existing = this.entries.get(key);\n\n if (!existing || existing.reset <= now) {\n // New window\n const reset = now + this.windowMs;\n this.entries.set(key, { count: 1, reset });\n return { count: 1, reset };\n }\n\n // Increment existing\n existing.count++;\n return { count: existing.count, reset: existing.reset };\n }\n\n get(key: string): StoreResult | undefined {\n const entry = this.entries.get(key);\n if (!entry || entry.reset <= Date.now()) {\n return undefined;\n }\n return { count: entry.count, reset: entry.reset };\n }\n\n decrement(key: string): void {\n const entry = this.entries.get(key);\n if (entry && entry.count > 0) {\n entry.count--;\n }\n }\n\n resetKey(key: string): void {\n this.entries.delete(key);\n }\n\n resetAll(): void {\n this.entries.clear();\n }\n\n shutdown(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n this.entries.clear();\n }\n}\n\n// Singleton default store\nlet defaultStore: MemoryStore | undefined;\n\n// ============================================================================\n// Header Generation\n// ============================================================================\n\n/**\n * Set rate limit response headers based on the configured format.\n *\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nfunction setHeaders(\n c: Context,\n info: RateLimitInfo,\n format: HeadersFormat,\n windowMs: number,\n identifier: string,\n quotaUnit: QuotaUnit,\n): void {\n if (format === false) {\n return;\n }\n\n const windowSeconds = Math.ceil(windowMs / 1000);\n const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n\n switch (format) {\n case \"standard\":\n // IETF draft-08+ (current): Structured field values per RFC 9651\n // RateLimit-Policy: describes the quota policy\n // Format: \"name\";q=<quota>;w=<window>[;qu=\"<unit>\"]\n {\n let policy = `\"${identifier}\";q=${info.limit};w=${windowSeconds}`;\n if (quotaUnit !== \"requests\") {\n policy += `;qu=\"${quotaUnit}\"`;\n }\n c.header(\"RateLimit-Policy\", policy);\n // RateLimit: describes current service limits\n // Format: \"name\";r=<remaining>;t=<reset>\n c.header(\n \"RateLimit\",\n `\"${identifier}\";r=${info.remaining};t=${resetSeconds}`,\n );\n }\n break;\n\n case \"draft-7\":\n // IETF draft-07: Combined RateLimit header with comma-separated values\n c.header(\"RateLimit-Policy\", `${info.limit};w=${windowSeconds}`);\n c.header(\n \"RateLimit\",\n `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`,\n );\n break;\n\n case \"draft-6\":\n // IETF draft-06: Individual RateLimit-* headers\n c.header(\"RateLimit-Policy\", `${info.limit};w=${windowSeconds}`);\n c.header(\"RateLimit-Limit\", String(info.limit));\n c.header(\"RateLimit-Remaining\", String(info.remaining));\n c.header(\"RateLimit-Reset\", String(resetSeconds));\n break;\n\n case \"legacy\":\n default:\n // Common X-RateLimit-* headers (GitHub, Twitter, most APIs)\n // Uses Unix timestamp for reset (seconds since epoch)\n c.header(\"X-RateLimit-Limit\", String(info.limit));\n c.header(\"X-RateLimit-Remaining\", String(info.remaining));\n c.header(\"X-RateLimit-Reset\", String(Math.ceil(info.reset / 1000)));\n break;\n }\n}\n\n// ============================================================================\n// Default Key Generator\n// ============================================================================\n\nfunction getClientIP(c: Context): string {\n // Platform-specific headers (most reliable)\n const cfIP = c.req.header(\"cf-connecting-ip\");\n if (cfIP) {\n return cfIP;\n }\n\n const xRealIP = c.req.header(\"x-real-ip\");\n if (xRealIP) {\n return xRealIP;\n }\n\n // X-Forwarded-For - take first IP\n const xff = c.req.header(\"x-forwarded-for\");\n if (xff) {\n return xff.split(\",\")[0].trim();\n }\n\n return \"unknown\";\n}\n\n// ============================================================================\n// Default Handler\n// ============================================================================\n\nfunction createDefaultResponse(info: RateLimitInfo): Response {\n const retryAfter = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n\n return new Response(\"Rate limit exceeded\", {\n status: 429,\n headers: {\n \"Content-Type\": \"text/plain\",\n \"Retry-After\": String(retryAfter),\n },\n });\n}\n\n// ============================================================================\n// Sliding Window Algorithm\n// ============================================================================\n\nasync function checkSlidingWindow(\n store: RateLimitStore,\n key: string,\n limit: number,\n windowMs: number,\n): Promise<{ allowed: boolean; info: RateLimitInfo }> {\n const now = Date.now();\n const currentWindowStart = Math.floor(now / windowMs) * windowMs;\n const previousWindowStart = currentWindowStart - windowMs;\n\n const previousKey = `${key}:${previousWindowStart}`;\n const currentKey = `${key}:${currentWindowStart}`;\n\n // Increment current window\n const current = await store.increment(currentKey);\n\n // Get previous window (may not exist)\n let previousCount = 0;\n if (store.get) {\n const prev = await store.get(previousKey);\n previousCount = prev?.count ?? 0;\n }\n\n // Cloudflare's weighted formula\n const elapsedMs = now - currentWindowStart;\n const weight = (windowMs - elapsedMs) / windowMs;\n const estimatedCount = Math.floor(previousCount * weight) + current.count;\n\n const remaining = Math.max(0, limit - estimatedCount);\n const allowed = estimatedCount <= limit;\n const reset = currentWindowStart + windowMs;\n\n return {\n allowed,\n info: { limit, remaining, reset },\n };\n}\n\n// ============================================================================\n// Fixed Window Algorithm\n// ============================================================================\n\nasync function checkFixedWindow(\n store: RateLimitStore,\n key: string,\n limit: number,\n windowMs: number,\n): Promise<{ allowed: boolean; info: RateLimitInfo }> {\n const now = Date.now();\n const windowStart = Math.floor(now / windowMs) * windowMs;\n const windowKey = `${key}:${windowStart}`;\n\n const { count, reset } = await store.increment(windowKey);\n\n const remaining = Math.max(0, limit - count);\n const allowed = count <= limit;\n\n return {\n allowed,\n info: { limit, remaining, reset },\n };\n}\n\n// ============================================================================\n// Main Middleware\n// ============================================================================\n\n/**\n * Rate Limit Middleware for Hono.\n *\n * @param {RateLimitOptions} [options] - Configuration options\n * @returns {MiddlewareHandler} Middleware handler\n *\n * @example\n * ```ts\n * import { Hono } from 'hono'\n * import { rateLimiter } from '@jellyfungus/hono-rate-limiter'\n *\n * const app = new Hono()\n *\n * // Basic usage - 60 requests per minute\n * app.use(rateLimiter())\n *\n * // Custom configuration\n * app.use('/api/*', rateLimiter({\n * limit: 100,\n * windowMs: 60 * 1000,\n * }))\n * ```\n */\nexport const rateLimiter = <E extends Env = Env>(\n options?: RateLimitOptions<E>,\n): MiddlewareHandler<E> => {\n // Merge with defaults\n const opts = {\n limit: 60 as number | ((c: Context<E>) => number | Promise<number>),\n windowMs: 60_000,\n algorithm: \"sliding-window\" as Algorithm,\n store: undefined as RateLimitStore | undefined,\n keyGenerator: getClientIP as (c: Context<E>) => string | Promise<string>,\n handler: undefined as\n | ((c: Context<E>, info: RateLimitInfo) => Response | Promise<Response>)\n | undefined,\n headers: \"legacy\" as HeadersFormat,\n identifier: \"default\",\n quotaUnit: \"requests\" as QuotaUnit,\n skip: undefined as\n | ((c: Context<E>) => boolean | Promise<boolean>)\n | undefined,\n skipSuccessfulRequests: false,\n skipFailedRequests: false,\n onRateLimited: undefined as\n | ((c: Context<E>, info: RateLimitInfo) => void | Promise<void>)\n | undefined,\n ...options,\n };\n\n // Use default store if none provided\n const store = opts.store ?? (defaultStore ??= new MemoryStore());\n\n // Track initialization\n let initialized = false;\n\n return async function rateLimiter(c, next) {\n // Initialize store on first request\n if (!initialized && store.init) {\n await store.init(opts.windowMs);\n initialized = true;\n }\n\n // Check if should skip\n if (opts.skip) {\n const shouldSkip = await opts.skip(c);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Generate key\n const key = await opts.keyGenerator(c);\n\n // Get limit (may be dynamic)\n const limit =\n typeof opts.limit === \"function\" ? await opts.limit(c) : opts.limit;\n\n // Check rate limit\n const { allowed, info } =\n opts.algorithm === \"sliding-window\"\n ? await checkSlidingWindow(store, key, limit, opts.windowMs)\n : await checkFixedWindow(store, key, limit, opts.windowMs);\n\n // Set context variable for downstream middleware\n c.set(\"rateLimit\", info);\n\n // Expose store access in context\n c.set(\"rateLimitStore\", {\n getKey: store.get?.bind(store) ?? (() => undefined),\n resetKey: store.resetKey.bind(store),\n });\n\n // Set headers\n setHeaders(\n c,\n info,\n opts.headers,\n opts.windowMs,\n opts.identifier,\n opts.quotaUnit,\n );\n\n // Handle rate limited\n if (!allowed) {\n // Fire callback\n if (opts.onRateLimited) {\n await opts.onRateLimited(c, info);\n }\n\n // Custom handler or default\n if (opts.handler) {\n return opts.handler(c, info);\n }\n return createDefaultResponse(info);\n }\n\n // Continue\n await next();\n\n // Handle skip options after response\n if (opts.skipSuccessfulRequests || opts.skipFailedRequests) {\n const status = c.res.status;\n const shouldDecrement =\n (opts.skipSuccessfulRequests && status >= 200 && status < 300) ||\n (opts.skipFailedRequests && status >= 400);\n\n if (shouldDecrement && store.decrement) {\n const windowStart =\n Math.floor(Date.now() / opts.windowMs) * opts.windowMs;\n const windowKey = `${key}:${windowStart}`;\n await store.decrement(windowKey);\n }\n }\n };\n};\n\n// ============================================================================\n// Cloudflare Rate Limiting Binding Middleware\n// ============================================================================\n\n/**\n * Rate limiter using Cloudflare's built-in Rate Limiting binding.\n *\n * This uses Cloudflare's globally distributed rate limiting infrastructure,\n * which is ideal for high-traffic applications.\n *\n * @example\n * ```ts\n * import { cloudflareRateLimiter } from '@jellyfungus/hono-rate-limiter'\n *\n * type Bindings = { RATE_LIMITER: RateLimitBinding }\n *\n * const app = new Hono<{ Bindings: Bindings }>()\n *\n * app.use(cloudflareRateLimiter({\n * binding: (c) => c.env.RATE_LIMITER,\n * keyGenerator: (c) => c.req.header('cf-connecting-ip') ?? 'unknown',\n * }))\n * ```\n */\nexport const cloudflareRateLimiter = <E extends Env = Env>(\n options: CloudflareRateLimitOptions<E>,\n): MiddlewareHandler<E> => {\n const { binding, keyGenerator, handler, skip } = options;\n\n return async function cloudflareRateLimiter(c, next) {\n // Check if should skip\n if (skip) {\n const shouldSkip = await skip(c);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Get binding (may be dynamic)\n const rateLimitBinding =\n typeof binding === \"function\" ? binding(c) : binding;\n\n // Generate key\n const key = await keyGenerator(c);\n\n // Check rate limit\n const { success } = await rateLimitBinding.limit({ key });\n\n if (!success) {\n if (handler) {\n return handler(c);\n }\n return new Response(\"Rate limit exceeded\", {\n status: 429,\n headers: { \"Content-Type\": \"text/plain\" },\n });\n }\n\n return next();\n };\n};\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport { getClientIP };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4RO,IAAM,cAAN,MAA4C;AAAA,EACzC,UAAU,oBAAI,IAAyB;AAAA,EACvC,WAAW;AAAA,EACX;AAAA,EAER,KAAK,UAAwB;AAC3B,SAAK,WAAW;AAGhB,SAAK,eAAe,YAAY,MAAM;AACpC,YAAM,MAAM,KAAK,IAAI;AACrB,iBAAW,CAAC,KAAK,KAAK,KAAK,KAAK,SAAS;AACvC,YAAI,MAAM,SAAS,KAAK;AACtB,eAAK,QAAQ,OAAO,GAAG;AAAA,QACzB;AAAA,MACF;AAAA,IACF,GAAG,GAAM;AAGT,QAAI,OAAO,KAAK,aAAa,UAAU,YAAY;AACjD,WAAK,aAAa,MAAM;AAAA,IAC1B;AAAA,EACF;AAAA,EAEA,UAAU,KAA0B;AAClC,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,WAAW,KAAK,QAAQ,IAAI,GAAG;AAErC,QAAI,CAAC,YAAY,SAAS,SAAS,KAAK;AAEtC,YAAM,QAAQ,MAAM,KAAK;AACzB,WAAK,QAAQ,IAAI,KAAK,EAAE,OAAO,GAAG,MAAM,CAAC;AACzC,aAAO,EAAE,OAAO,GAAG,MAAM;AAAA,IAC3B;AAGA,aAAS;AACT,WAAO,EAAE,OAAO,SAAS,OAAO,OAAO,SAAS,MAAM;AAAA,EACxD;AAAA,EAEA,IAAI,KAAsC;AACxC,UAAM,QAAQ,KAAK,QAAQ,IAAI,GAAG;AAClC,QAAI,CAAC,SAAS,MAAM,SAAS,KAAK,IAAI,GAAG;AACvC,aAAO;AAAA,IACT;AACA,WAAO,EAAE,OAAO,MAAM,OAAO,OAAO,MAAM,MAAM;AAAA,EAClD;AAAA,EAEA,UAAU,KAAmB;AAC3B,UAAM,QAAQ,KAAK,QAAQ,IAAI,GAAG;AAClC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,MAAM,UAAU,SAAS;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AACF;AA0BO,IAAM,wBAAwB,CACnC,YACyB;AACzB,QAAM,EAAE,SAAS,cAAc,SAAS,KAAK,IAAI;AAEjD,SAAO,eAAeC,uBAAsB,GAAG,MAAM;AAEnD,QAAI,MAAM;AACR,YAAM,aAAa,MAAM,KAAK,CAAC;AAC/B,UAAI,YAAY;AACd,eAAO,KAAK;AAAA,MACd;AAAA,IACF;AAGA,UAAM,mBACJ,OAAO,YAAY,aAAa,QAAQ,CAAC,IAAI;AAG/C,UAAM,MAAM,MAAM,aAAa,CAAC;AAGhC,UAAM,EAAE,QAAQ,IAAI,MAAM,iBAAiB,MAAM,EAAE,IAAI,CAAC;AAExD,QAAI,CAAC,SAAS;AACZ,UAAI,SAAS;AACX,eAAO,QAAQ,CAAC;AAAA,MAClB;AACA,aAAO,IAAI,SAAS,uBAAuB;AAAA,QACzC,QAAQ;AAAA,QACR,SAAS,EAAE,gBAAgB,aAAa;AAAA,MAC1C,CAAC;AAAA,IACH;AAEA,WAAO,KAAK;AAAA,EACd;AACF;","names":["rateLimiter","cloudflareRateLimiter"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @module\n * Rate Limit Middleware for Hono.\n */\n\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Rate limit information for a single request\n */\nexport type RateLimitInfo = {\n /** Maximum requests allowed in window */\n limit: number;\n /** Remaining requests in current window */\n remaining: number;\n /** Unix timestamp (ms) when window resets */\n reset: number;\n};\n\n/**\n * Result from store increment operation\n */\nexport type StoreResult = {\n /** Current request count in window */\n count: number;\n /** When the window resets (Unix timestamp ms) */\n reset: number;\n};\n\n/**\n * Quota unit for IETF standard headers.\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nexport type QuotaUnit = \"requests\" | \"content-bytes\" | \"concurrent-requests\";\n\n/**\n * Header format options.\n *\n * ## \"legacy\" (default)\n * Common X-RateLimit-* headers used by GitHub, Twitter, and most APIs:\n * - `X-RateLimit-Limit`: max requests in window\n * - `X-RateLimit-Remaining`: remaining requests\n * - `X-RateLimit-Reset`: Unix timestamp (seconds) when window resets\n *\n * ## \"draft-6\"\n * IETF draft-06 format with individual RateLimit-* headers:\n * - `RateLimit-Policy`: policy description (e.g., `100;w=60`)\n * - `RateLimit-Limit`: max requests\n * - `RateLimit-Remaining`: remaining requests\n * - `RateLimit-Reset`: seconds until reset\n *\n * ## \"draft-7\"\n * IETF draft-07 format with combined RateLimit header:\n * - `RateLimit-Policy`: policy description\n * - `RateLimit`: combined (e.g., `limit=100, remaining=50, reset=30`)\n *\n * ## \"standard\"\n * Current IETF draft-08+ format with structured field values (RFC 9651):\n * - `RateLimit-Policy`: `\"name\";q=100;w=60`\n * - `RateLimit`: `\"name\";r=50;t=30`\n *\n * ## false\n * Disable all rate limit headers.\n *\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nexport type HeadersFormat =\n | \"legacy\" // X-RateLimit-* headers (GitHub/Twitter style)\n | \"draft-6\" // IETF draft-06: individual RateLimit-* headers\n | \"draft-7\" // IETF draft-07: combined RateLimit header\n | \"standard\" // IETF draft-08+: structured field format (current)\n | false; // Disable headers\n\n/**\n * Rate limit algorithm\n */\nexport type Algorithm = \"fixed-window\" | \"sliding-window\";\n\n/**\n * Store interface for rate limit state\n */\nexport type RateLimitStore = {\n /**\n * Initialize store. Called once before first use.\n */\n init?: (windowMs: number) => void | Promise<void>;\n\n /**\n * Increment counter for key and return current state.\n */\n increment: (key: string) => StoreResult | Promise<StoreResult>;\n\n /**\n * Decrement counter for key.\n */\n decrement?: (key: string) => void | Promise<void>;\n\n /**\n * Reset a specific key.\n */\n resetKey: (key: string) => void | Promise<void>;\n\n /**\n * Reset all keys.\n */\n resetAll?: () => void | Promise<void>;\n\n /**\n * Get current state for key.\n */\n get?: (\n key: string,\n ) => StoreResult | Promise<StoreResult | undefined> | undefined;\n\n /**\n * Graceful shutdown.\n */\n shutdown?: () => void | Promise<void>;\n};\n\n/**\n * Store access interface exposed in context\n */\nexport type RateLimitStoreAccess = {\n /** Get rate limit info for a key */\n getKey: (\n key: string,\n ) => StoreResult | Promise<StoreResult | undefined> | undefined;\n /** Reset rate limit for a key */\n resetKey: (key: string) => void | Promise<void>;\n};\n\n/**\n * Options for rate limit middleware\n */\nexport type RateLimitOptions<E extends Env = Env> = {\n /**\n * Maximum requests allowed in the time window.\n * @default 60\n */\n limit?: number | ((c: Context<E>) => number | Promise<number>);\n\n /**\n * Time window in milliseconds.\n * @default 60000 (1 minute)\n */\n windowMs?: number;\n\n /**\n * Rate limiting algorithm.\n * @default 'sliding-window'\n */\n algorithm?: Algorithm;\n\n /**\n * Storage backend for rate limit state.\n * @default MemoryStore\n */\n store?: RateLimitStore;\n\n /**\n * Generate unique key for each client.\n * @default IP address from headers\n */\n keyGenerator?: (c: Context<E>) => string | Promise<string>;\n\n /**\n * Handler called when rate limit is exceeded.\n */\n handler?: (\n c: Context<E>,\n info: RateLimitInfo,\n ) => Response | Promise<Response>;\n\n /**\n * HTTP header format to use.\n *\n * - \"legacy\": X-RateLimit-* headers (GitHub/Twitter style, default)\n * - \"draft-6\": IETF draft-06 individual headers\n * - \"draft-7\": IETF draft-07 combined header\n * - \"standard\": IETF draft-08+ structured fields (current spec)\n * - false: Disable headers\n *\n * @default 'legacy'\n */\n headers?: HeadersFormat;\n\n /**\n * Policy identifier for IETF headers (draft-6+).\n * Used in RateLimit and RateLimit-Policy headers.\n * @default 'default'\n */\n identifier?: string;\n\n /**\n * Quota unit for IETF standard headers.\n * Only included in \"standard\" format when not \"requests\".\n * @default 'requests'\n */\n quotaUnit?: QuotaUnit;\n\n /**\n * Skip rate limiting for certain requests.\n */\n skip?: (c: Context<E>) => boolean | Promise<boolean>;\n\n /**\n * Don't count successful (2xx) requests against limit.\n * @default false\n */\n skipSuccessfulRequests?: boolean;\n\n /**\n * Don't count failed (4xx, 5xx) requests against limit.\n * @default false\n */\n skipFailedRequests?: boolean;\n\n /**\n * Callback when a request is rate limited.\n */\n onRateLimited?: (c: Context<E>, info: RateLimitInfo) => void | Promise<void>;\n\n /**\n * Behavior when store operations fail.\n *\n * - 'allow': Allow the request through (fail-open, default)\n * - 'deny': Block the request with 500 error (fail-closed)\n * - Function: Custom handler returning true to allow, false to deny\n *\n * @default 'allow'\n */\n onStoreError?:\n | \"allow\"\n | \"deny\"\n | ((error: Error, c: Context<E>) => boolean | Promise<boolean>);\n};\n\n/**\n * Cloudflare Rate Limiting binding interface\n */\nexport type RateLimitBinding = {\n limit: (options: { key: string }) => Promise<{ success: boolean }>;\n};\n\n/**\n * Options for Cloudflare Rate Limiting binding\n */\nexport type CloudflareRateLimitOptions<E extends Env = Env> = {\n /**\n * Cloudflare Rate Limiting binding from env\n */\n binding: RateLimitBinding | ((c: Context<E>) => RateLimitBinding);\n\n /**\n * Generate unique key for each client.\n */\n keyGenerator: (c: Context<E>) => string | Promise<string>;\n\n /**\n * Handler called when rate limit is exceeded.\n */\n handler?: (c: Context<E>) => Response | Promise<Response>;\n\n /**\n * Skip rate limiting for certain requests.\n */\n skip?: (c: Context<E>) => boolean | Promise<boolean>;\n};\n\n// ============================================================================\n// Context Variable Type Extension\n// ============================================================================\n\ndeclare module \"hono\" {\n interface ContextVariableMap {\n rateLimit?: RateLimitInfo;\n rateLimitStore?: RateLimitStoreAccess;\n }\n}\n\n// ============================================================================\n// Memory Store\n// ============================================================================\n\ntype MemoryEntry = {\n count: number;\n reset: number;\n};\n\n/**\n * In-memory store for rate limiting.\n * Suitable for single-instance deployments.\n */\nexport class MemoryStore implements RateLimitStore {\n private entries = new Map<string, MemoryEntry>();\n private windowMs = 60_000;\n private cleanupTimer?: ReturnType<typeof setInterval>;\n\n init(windowMs: number): void {\n this.windowMs = windowMs;\n\n // Cleanup expired entries every minute\n this.cleanupTimer = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of this.entries) {\n if (entry.reset <= now) {\n this.entries.delete(key);\n }\n }\n }, 60_000);\n\n // Don't keep process alive for cleanup\n if (typeof this.cleanupTimer.unref === \"function\") {\n this.cleanupTimer.unref();\n }\n }\n\n increment(key: string): StoreResult {\n const now = Date.now();\n const existing = this.entries.get(key);\n\n if (!existing || existing.reset <= now) {\n // New window\n const reset = now + this.windowMs;\n this.entries.set(key, { count: 1, reset });\n return { count: 1, reset };\n }\n\n // Increment existing\n existing.count++;\n return { count: existing.count, reset: existing.reset };\n }\n\n get(key: string): StoreResult | undefined {\n const entry = this.entries.get(key);\n if (!entry || entry.reset <= Date.now()) {\n return undefined;\n }\n return { count: entry.count, reset: entry.reset };\n }\n\n decrement(key: string): void {\n const entry = this.entries.get(key);\n if (entry && entry.count > 0) {\n entry.count--;\n }\n }\n\n resetKey(key: string): void {\n this.entries.delete(key);\n }\n\n resetAll(): void {\n this.entries.clear();\n }\n\n shutdown(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n this.entries.clear();\n }\n}\n\n// Singleton default store\nlet defaultStore: MemoryStore | undefined;\n\n/**\n * Shutdown the default memory store.\n * Call this during graceful shutdown to clean up timers.\n *\n * @example\n * ```ts\n * import { shutdownDefaultStore } from '@jellyfungus/hono-rate-limiter'\n *\n * process.on('SIGTERM', () => {\n * shutdownDefaultStore()\n * process.exit(0)\n * })\n * ```\n */\nexport function shutdownDefaultStore(): void {\n if (defaultStore) {\n defaultStore.shutdown();\n defaultStore = undefined;\n }\n}\n\n// ============================================================================\n// Header Generation\n// ============================================================================\n\n/**\n * Set rate limit response headers based on the configured format.\n *\n * @see https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/\n */\nfunction setHeaders(\n c: Context,\n info: RateLimitInfo,\n format: HeadersFormat,\n windowMs: number,\n identifier: string,\n quotaUnit: QuotaUnit,\n): void {\n if (format === false) {\n return;\n }\n\n const windowSeconds = Math.ceil(windowMs / 1000);\n const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n const safeId = sanitizeIdentifier(identifier);\n\n switch (format) {\n case \"standard\":\n // IETF draft-08+ (current): Structured field values per RFC 9651\n // RateLimit-Policy: describes the quota policy\n // Format: \"name\";q=<quota>;w=<window>[;qu=\"<unit>\"]\n {\n let policy = `\"${safeId}\";q=${info.limit};w=${windowSeconds}`;\n if (quotaUnit !== \"requests\") {\n policy += `;qu=\"${quotaUnit}\"`;\n }\n c.header(\"RateLimit-Policy\", policy);\n // RateLimit: describes current service limits\n // Format: \"name\";r=<remaining>;t=<reset>\n c.header(\n \"RateLimit\",\n `\"${safeId}\";r=${info.remaining};t=${resetSeconds}`,\n );\n }\n break;\n\n case \"draft-7\":\n // IETF draft-07: Combined RateLimit header with comma-separated values\n c.header(\"RateLimit-Policy\", `${info.limit};w=${windowSeconds}`);\n c.header(\n \"RateLimit\",\n `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`,\n );\n break;\n\n case \"draft-6\":\n // IETF draft-06: Individual RateLimit-* headers\n c.header(\"RateLimit-Policy\", `${info.limit};w=${windowSeconds}`);\n c.header(\"RateLimit-Limit\", String(info.limit));\n c.header(\"RateLimit-Remaining\", String(info.remaining));\n c.header(\"RateLimit-Reset\", String(resetSeconds));\n break;\n\n case \"legacy\":\n default:\n // Common X-RateLimit-* headers (GitHub, Twitter, most APIs)\n // Uses Unix timestamp for reset (seconds since epoch)\n c.header(\"X-RateLimit-Limit\", String(info.limit));\n c.header(\"X-RateLimit-Remaining\", String(info.remaining));\n c.header(\"X-RateLimit-Reset\", String(Math.ceil(info.reset / 1000)));\n break;\n }\n}\n\n// ============================================================================\n// Identifier Sanitization\n// ============================================================================\n\n/**\n * Sanitize identifier for RFC 9651 structured field compliance.\n * Identifiers are used in the RateLimit and RateLimit-Policy headers.\n */\nfunction sanitizeIdentifier(id: string): string {\n if (!id || typeof id !== \"string\") {\n return \"default\";\n }\n // RFC 9651 tokens: Only allow alphanumeric, underscore, hyphen, dot, colon, asterisk, slash\n // Must start with a letter\n const sanitized = id.replace(/[^a-zA-Z0-9_\\-.:*/]/g, \"-\");\n if (!sanitized || !/^[a-zA-Z]/.test(sanitized)) {\n return \"default\";\n }\n return sanitized;\n}\n\n// ============================================================================\n// Default Key Generator\n// ============================================================================\n\nfunction getClientIP(c: Context): string {\n // Platform-specific headers (most reliable)\n const cfIP = c.req.header(\"cf-connecting-ip\");\n if (cfIP) {\n return cfIP;\n }\n\n const xRealIP = c.req.header(\"x-real-ip\");\n if (xRealIP) {\n return xRealIP;\n }\n\n // X-Forwarded-For - take first IP\n const xff = c.req.header(\"x-forwarded-for\");\n if (xff) {\n return xff.split(\",\")[0].trim();\n }\n\n return \"unknown\";\n}\n\n// ============================================================================\n// Default Handler\n// ============================================================================\n\n/**\n * Build headers object for rate limit responses.\n * This ensures headers are included in both custom and default responses.\n */\nfunction buildRateLimitHeaders(\n info: RateLimitInfo,\n format: HeadersFormat,\n windowMs: number,\n identifier: string,\n quotaUnit: QuotaUnit,\n): Record<string, string> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"text/plain\",\n \"Retry-After\": String(\n Math.max(0, Math.ceil((info.reset - Date.now()) / 1000)),\n ),\n };\n\n if (format === false) {\n return headers;\n }\n\n const windowSeconds = Math.ceil(windowMs / 1000);\n const resetSeconds = Math.max(0, Math.ceil((info.reset - Date.now()) / 1000));\n const safeId = sanitizeIdentifier(identifier);\n\n switch (format) {\n case \"standard\": {\n let policy = `\"${safeId}\";q=${info.limit};w=${windowSeconds}`;\n if (quotaUnit !== \"requests\") {\n policy += `;qu=\"${quotaUnit}\"`;\n }\n headers[\"RateLimit-Policy\"] = policy;\n headers[\"RateLimit\"] =\n `\"${safeId}\";r=${info.remaining};t=${resetSeconds}`;\n break;\n }\n case \"draft-7\":\n headers[\"RateLimit-Policy\"] = `${info.limit};w=${windowSeconds}`;\n headers[\"RateLimit\"] =\n `limit=${info.limit}, remaining=${info.remaining}, reset=${resetSeconds}`;\n break;\n case \"draft-6\":\n headers[\"RateLimit-Policy\"] = `${info.limit};w=${windowSeconds}`;\n headers[\"RateLimit-Limit\"] = String(info.limit);\n headers[\"RateLimit-Remaining\"] = String(info.remaining);\n headers[\"RateLimit-Reset\"] = String(resetSeconds);\n break;\n case \"legacy\":\n default:\n headers[\"X-RateLimit-Limit\"] = String(info.limit);\n headers[\"X-RateLimit-Remaining\"] = String(info.remaining);\n headers[\"X-RateLimit-Reset\"] = String(Math.ceil(info.reset / 1000));\n break;\n }\n\n return headers;\n}\n\nfunction createDefaultResponse(\n info: RateLimitInfo,\n format: HeadersFormat,\n windowMs: number,\n identifier: string,\n quotaUnit: QuotaUnit,\n): Response {\n const headers = buildRateLimitHeaders(\n info,\n format,\n windowMs,\n identifier,\n quotaUnit,\n );\n\n return new Response(\"Rate limit exceeded\", {\n status: 429,\n headers,\n });\n}\n\n// ============================================================================\n// Sliding Window Algorithm\n// ============================================================================\n\nasync function checkSlidingWindow(\n store: RateLimitStore,\n key: string,\n limit: number,\n windowMs: number,\n): Promise<{ allowed: boolean; info: RateLimitInfo }> {\n const now = Date.now();\n const currentWindowStart = Math.floor(now / windowMs) * windowMs;\n const previousWindowStart = currentWindowStart - windowMs;\n\n const previousKey = `${key}:${previousWindowStart}`;\n const currentKey = `${key}:${currentWindowStart}`;\n\n // Increment current window\n const current = await store.increment(currentKey);\n\n // Get previous window (may not exist)\n let previousCount = 0;\n if (store.get) {\n const prev = await store.get(previousKey);\n previousCount = prev?.count ?? 0;\n }\n\n // Cloudflare's weighted formula\n const elapsedMs = now - currentWindowStart;\n const weight = (windowMs - elapsedMs) / windowMs;\n const estimatedCount = Math.floor(previousCount * weight) + current.count;\n\n const remaining = Math.max(0, limit - estimatedCount);\n const allowed = estimatedCount <= limit;\n const reset = currentWindowStart + windowMs;\n\n return {\n allowed,\n info: { limit, remaining, reset },\n };\n}\n\n// ============================================================================\n// Fixed Window Algorithm\n// ============================================================================\n\nasync function checkFixedWindow(\n store: RateLimitStore,\n key: string,\n limit: number,\n windowMs: number,\n): Promise<{ allowed: boolean; info: RateLimitInfo }> {\n const now = Date.now();\n const windowStart = Math.floor(now / windowMs) * windowMs;\n const windowKey = `${key}:${windowStart}`;\n\n const { count, reset } = await store.increment(windowKey);\n\n const remaining = Math.max(0, limit - count);\n const allowed = count <= limit;\n\n return {\n allowed,\n info: { limit, remaining, reset },\n };\n}\n\n// ============================================================================\n// Main Middleware\n// ============================================================================\n\n/**\n * Rate Limit Middleware for Hono.\n *\n * @param {RateLimitOptions} [options] - Configuration options\n * @returns {MiddlewareHandler} Middleware handler\n *\n * @example\n * ```ts\n * import { Hono } from 'hono'\n * import { rateLimiter } from '@jellyfungus/hono-rate-limiter'\n *\n * const app = new Hono()\n *\n * // Basic usage - 60 requests per minute\n * app.use(rateLimiter())\n *\n * // Custom configuration\n * app.use('/api/*', rateLimiter({\n * limit: 100,\n * windowMs: 60 * 1000,\n * }))\n * ```\n */\nexport const rateLimiter = <E extends Env = Env>(\n options?: RateLimitOptions<E>,\n): MiddlewareHandler<E> => {\n // Merge with defaults\n const opts = {\n limit: 60 as number | ((c: Context<E>) => number | Promise<number>),\n windowMs: 60_000,\n algorithm: \"sliding-window\" as Algorithm,\n store: undefined as RateLimitStore | undefined,\n keyGenerator: getClientIP as (c: Context<E>) => string | Promise<string>,\n handler: undefined as\n | ((c: Context<E>, info: RateLimitInfo) => Response | Promise<Response>)\n | undefined,\n headers: \"legacy\" as HeadersFormat,\n identifier: \"default\",\n quotaUnit: \"requests\" as QuotaUnit,\n skip: undefined as\n | ((c: Context<E>) => boolean | Promise<boolean>)\n | undefined,\n skipSuccessfulRequests: false,\n skipFailedRequests: false,\n onRateLimited: undefined as\n | ((c: Context<E>, info: RateLimitInfo) => void | Promise<void>)\n | undefined,\n onStoreError: \"allow\" as\n | \"allow\"\n | \"deny\"\n | ((error: Error, c: Context<E>) => boolean | Promise<boolean>),\n ...options,\n };\n\n // Use default store if none provided\n const store = opts.store ?? (defaultStore ??= new MemoryStore());\n\n // Track initialization\n let initPromise: Promise<void> | null = null;\n\n /**\n * Handle store errors based on configuration.\n * @returns true to allow request, false to deny\n */\n async function handleStoreError(\n error: Error,\n c: Context<E>,\n ): Promise<boolean> {\n if (typeof opts.onStoreError === \"function\") {\n return opts.onStoreError(error, c);\n }\n // Default: fail-open (allow request through)\n return opts.onStoreError === \"allow\";\n }\n\n return async function rateLimiter(c, next) {\n // Initialize store on first request (with proper locking)\n if (!initPromise && store.init) {\n const result = store.init(opts.windowMs);\n // Handle both sync and async init\n initPromise = result instanceof Promise ? result : Promise.resolve();\n }\n if (initPromise) {\n try {\n await initPromise;\n } catch (error) {\n const shouldAllow = await handleStoreError(\n error instanceof Error ? error : new Error(String(error)),\n c,\n );\n if (shouldAllow) {\n return next();\n }\n return new Response(\"Rate limiter initialization failed\", {\n status: 500,\n });\n }\n }\n\n // Check if should skip\n if (opts.skip) {\n const shouldSkip = await opts.skip(c);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Generate key\n const key = await opts.keyGenerator(c);\n\n // Get limit (may be dynamic)\n const limit =\n typeof opts.limit === \"function\" ? await opts.limit(c) : opts.limit;\n\n // Check rate limit with error handling\n let allowed: boolean;\n let info: RateLimitInfo;\n\n try {\n const result =\n opts.algorithm === \"sliding-window\"\n ? await checkSlidingWindow(store, key, limit, opts.windowMs)\n : await checkFixedWindow(store, key, limit, opts.windowMs);\n allowed = result.allowed;\n info = result.info;\n } catch (error) {\n const shouldAllow = await handleStoreError(\n error instanceof Error ? error : new Error(String(error)),\n c,\n );\n if (shouldAllow) {\n return next();\n }\n return new Response(\"Rate limiter error\", { status: 500 });\n }\n\n // Set context variable for downstream middleware\n c.set(\"rateLimit\", info);\n\n // Expose store access in context\n c.set(\"rateLimitStore\", {\n getKey: store.get?.bind(store) ?? (() => undefined),\n resetKey: store.resetKey.bind(store),\n });\n\n // Set headers\n setHeaders(\n c,\n info,\n opts.headers,\n opts.windowMs,\n opts.identifier,\n opts.quotaUnit,\n );\n\n // Handle rate limited\n if (!allowed) {\n // Fire callback\n if (opts.onRateLimited) {\n await opts.onRateLimited(c, info);\n }\n\n // Custom handler or default\n if (opts.handler) {\n return opts.handler(c, info);\n }\n return createDefaultResponse(\n info,\n opts.headers,\n opts.windowMs,\n opts.identifier,\n opts.quotaUnit,\n );\n }\n\n // Continue\n await next();\n\n // Handle skip options after response\n if (opts.skipSuccessfulRequests || opts.skipFailedRequests) {\n const status = c.res.status;\n const shouldDecrement =\n (opts.skipSuccessfulRequests && status >= 200 && status < 300) ||\n (opts.skipFailedRequests && status >= 400);\n\n if (shouldDecrement && store.decrement) {\n const windowStart =\n Math.floor(Date.now() / opts.windowMs) * opts.windowMs;\n const windowKey = `${key}:${windowStart}`;\n try {\n await store.decrement(windowKey);\n } catch {\n // Ignore decrement errors - request already processed\n }\n }\n }\n };\n};\n\n// ============================================================================\n// Cloudflare Rate Limiting Binding Middleware\n// ============================================================================\n\n/**\n * Rate limiter using Cloudflare's built-in Rate Limiting binding.\n *\n * This uses Cloudflare's globally distributed rate limiting infrastructure,\n * which is ideal for high-traffic applications.\n *\n * @example\n * ```ts\n * import { cloudflareRateLimiter } from '@jellyfungus/hono-rate-limiter'\n *\n * type Bindings = { RATE_LIMITER: RateLimitBinding }\n *\n * const app = new Hono<{ Bindings: Bindings }>()\n *\n * app.use(cloudflareRateLimiter({\n * binding: (c) => c.env.RATE_LIMITER,\n * keyGenerator: (c) => c.req.header('cf-connecting-ip') ?? 'unknown',\n * }))\n * ```\n */\nexport const cloudflareRateLimiter = <E extends Env = Env>(\n options: CloudflareRateLimitOptions<E>,\n): MiddlewareHandler<E> => {\n const { binding, keyGenerator, handler, skip } = options;\n\n return async function cloudflareRateLimiter(c, next) {\n // Check if should skip\n if (skip) {\n const shouldSkip = await skip(c);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Get binding (may be dynamic)\n const rateLimitBinding =\n typeof binding === \"function\" ? binding(c) : binding;\n\n // Generate key\n const key = await keyGenerator(c);\n\n // Check rate limit\n const { success } = await rateLimitBinding.limit({ key });\n\n if (!success) {\n if (handler) {\n return handler(c);\n }\n return new Response(\"Rate limit exceeded\", {\n status: 429,\n headers: { \"Content-Type\": \"text/plain\" },\n });\n }\n\n return next();\n };\n};\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport { getClientIP };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0SO,IAAM,cAAN,MAA4C;AAAA,EACzC,UAAU,oBAAI,IAAyB;AAAA,EACvC,WAAW;AAAA,EACX;AAAA,EAER,KAAK,UAAwB;AAC3B,SAAK,WAAW;AAGhB,SAAK,eAAe,YAAY,MAAM;AACpC,YAAM,MAAM,KAAK,IAAI;AACrB,iBAAW,CAAC,KAAK,KAAK,KAAK,KAAK,SAAS;AACvC,YAAI,MAAM,SAAS,KAAK;AACtB,eAAK,QAAQ,OAAO,GAAG;AAAA,QACzB;AAAA,MACF;AAAA,IACF,GAAG,GAAM;AAGT,QAAI,OAAO,KAAK,aAAa,UAAU,YAAY;AACjD,WAAK,aAAa,MAAM;AAAA,IAC1B;AAAA,EACF;AAAA,EAEA,UAAU,KAA0B;AAClC,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,WAAW,KAAK,QAAQ,IAAI,GAAG;AAErC,QAAI,CAAC,YAAY,SAAS,SAAS,KAAK;AAEtC,YAAM,QAAQ,MAAM,KAAK;AACzB,WAAK,QAAQ,IAAI,KAAK,EAAE,OAAO,GAAG,MAAM,CAAC;AACzC,aAAO,EAAE,OAAO,GAAG,MAAM;AAAA,IAC3B;AAGA,aAAS;AACT,WAAO,EAAE,OAAO,SAAS,OAAO,OAAO,SAAS,MAAM;AAAA,EACxD;AAAA,EAEA,IAAI,KAAsC;AACxC,UAAM,QAAQ,KAAK,QAAQ,IAAI,GAAG;AAClC,QAAI,CAAC,SAAS,MAAM,SAAS,KAAK,IAAI,GAAG;AACvC,aAAO;AAAA,IACT;AACA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UAAU;AAExC,UAAI,mBAAmB,MAAM,WAAW;AACtC,cAAM,cACJ,KAAK,MAAM,KAAK,IAAI,IAAI,KAAK,QAAQ,IAAI,KAAK;AAChD,cAAM,YAAY,GAAG,GAAG,IAAI,WAAW;AACvC,YAAI;AACF,gBAAM,MAAM,UAAU,SAAS;AAAA,QACjC,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AA0BO,IAAM,wBAAwB,CACnC,YACyB;AACzB,QAAM,EAAE,SAAS,cAAc,SAAS,KAAK,IAAI;AAEjD,SAAO,eAAeC,uBAAsB,GAAG,MAAM;AAEnD,QAAI,MAAM;AACR,YAAM,aAAa,MAAM,KAAK,CAAC;AAC/B,UAAI,YAAY;AACd,eAAO,KAAK;AAAA,MACd;AAAA,IACF;AAGA,UAAM,mBACJ,OAAO,YAAY,aAAa,QAAQ,CAAC,IAAI;AAG/C,UAAM,MAAM,MAAM,aAAa,CAAC;AAGhC,UAAM,EAAE,QAAQ,IAAI,MAAM,iBAAiB,MAAM,EAAE,IAAI,CAAC;AAExD,QAAI,CAAC,SAAS;AACZ,UAAI,SAAS;AACX,eAAO,QAAQ,CAAC;AAAA,MAClB;AACA,aAAO,IAAI,SAAS,uBAAuB;AAAA,QACzC,QAAQ;AAAA,QACR,SAAS,EAAE,gBAAgB,aAAa;AAAA,MAC1C,CAAC;AAAA,IACH;AAEA,WAAO,KAAK;AAAA,EACd;AACF;","names":["rateLimiter","cloudflareRateLimiter"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -183,6 +183,16 @@ type RateLimitOptions<E extends Env = Env> = {
|
|
|
183
183
|
* Callback when a request is rate limited.
|
|
184
184
|
*/
|
|
185
185
|
onRateLimited?: (c: Context<E>, info: RateLimitInfo) => void | Promise<void>;
|
|
186
|
+
/**
|
|
187
|
+
* Behavior when store operations fail.
|
|
188
|
+
*
|
|
189
|
+
* - 'allow': Allow the request through (fail-open, default)
|
|
190
|
+
* - 'deny': Block the request with 500 error (fail-closed)
|
|
191
|
+
* - Function: Custom handler returning true to allow, false to deny
|
|
192
|
+
*
|
|
193
|
+
* @default 'allow'
|
|
194
|
+
*/
|
|
195
|
+
onStoreError?: "allow" | "deny" | ((error: Error, c: Context<E>) => boolean | Promise<boolean>);
|
|
186
196
|
};
|
|
187
197
|
/**
|
|
188
198
|
* Cloudflare Rate Limiting binding interface
|
|
@@ -237,6 +247,21 @@ declare class MemoryStore implements RateLimitStore {
|
|
|
237
247
|
resetAll(): void;
|
|
238
248
|
shutdown(): void;
|
|
239
249
|
}
|
|
250
|
+
/**
|
|
251
|
+
* Shutdown the default memory store.
|
|
252
|
+
* Call this during graceful shutdown to clean up timers.
|
|
253
|
+
*
|
|
254
|
+
* @example
|
|
255
|
+
* ```ts
|
|
256
|
+
* import { shutdownDefaultStore } from '@jellyfungus/hono-rate-limiter'
|
|
257
|
+
*
|
|
258
|
+
* process.on('SIGTERM', () => {
|
|
259
|
+
* shutdownDefaultStore()
|
|
260
|
+
* process.exit(0)
|
|
261
|
+
* })
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
264
|
+
declare function shutdownDefaultStore(): void;
|
|
240
265
|
declare function getClientIP(c: Context): string;
|
|
241
266
|
/**
|
|
242
267
|
* Rate Limit Middleware for Hono.
|
|
@@ -284,4 +309,4 @@ declare const rateLimiter: <E extends Env = Env>(options?: RateLimitOptions<E>)
|
|
|
284
309
|
*/
|
|
285
310
|
declare const cloudflareRateLimiter: <E extends Env = Env>(options: CloudflareRateLimitOptions<E>) => MiddlewareHandler<E>;
|
|
286
311
|
|
|
287
|
-
export { type Algorithm, type CloudflareRateLimitOptions, type HeadersFormat, MemoryStore, type QuotaUnit, type RateLimitBinding, type RateLimitInfo, type RateLimitOptions, type RateLimitStore, type RateLimitStoreAccess, type StoreResult, cloudflareRateLimiter, getClientIP, rateLimiter };
|
|
312
|
+
export { type Algorithm, type CloudflareRateLimitOptions, type HeadersFormat, MemoryStore, type QuotaUnit, type RateLimitBinding, type RateLimitInfo, type RateLimitOptions, type RateLimitStore, type RateLimitStoreAccess, type StoreResult, cloudflareRateLimiter, getClientIP, rateLimiter, shutdownDefaultStore };
|
package/dist/index.d.ts
CHANGED
|
@@ -183,6 +183,16 @@ type RateLimitOptions<E extends Env = Env> = {
|
|
|
183
183
|
* Callback when a request is rate limited.
|
|
184
184
|
*/
|
|
185
185
|
onRateLimited?: (c: Context<E>, info: RateLimitInfo) => void | Promise<void>;
|
|
186
|
+
/**
|
|
187
|
+
* Behavior when store operations fail.
|
|
188
|
+
*
|
|
189
|
+
* - 'allow': Allow the request through (fail-open, default)
|
|
190
|
+
* - 'deny': Block the request with 500 error (fail-closed)
|
|
191
|
+
* - Function: Custom handler returning true to allow, false to deny
|
|
192
|
+
*
|
|
193
|
+
* @default 'allow'
|
|
194
|
+
*/
|
|
195
|
+
onStoreError?: "allow" | "deny" | ((error: Error, c: Context<E>) => boolean | Promise<boolean>);
|
|
186
196
|
};
|
|
187
197
|
/**
|
|
188
198
|
* Cloudflare Rate Limiting binding interface
|
|
@@ -237,6 +247,21 @@ declare class MemoryStore implements RateLimitStore {
|
|
|
237
247
|
resetAll(): void;
|
|
238
248
|
shutdown(): void;
|
|
239
249
|
}
|
|
250
|
+
/**
|
|
251
|
+
* Shutdown the default memory store.
|
|
252
|
+
* Call this during graceful shutdown to clean up timers.
|
|
253
|
+
*
|
|
254
|
+
* @example
|
|
255
|
+
* ```ts
|
|
256
|
+
* import { shutdownDefaultStore } from '@jellyfungus/hono-rate-limiter'
|
|
257
|
+
*
|
|
258
|
+
* process.on('SIGTERM', () => {
|
|
259
|
+
* shutdownDefaultStore()
|
|
260
|
+
* process.exit(0)
|
|
261
|
+
* })
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
264
|
+
declare function shutdownDefaultStore(): void;
|
|
240
265
|
declare function getClientIP(c: Context): string;
|
|
241
266
|
/**
|
|
242
267
|
* Rate Limit Middleware for Hono.
|
|
@@ -284,4 +309,4 @@ declare const rateLimiter: <E extends Env = Env>(options?: RateLimitOptions<E>)
|
|
|
284
309
|
*/
|
|
285
310
|
declare const cloudflareRateLimiter: <E extends Env = Env>(options: CloudflareRateLimitOptions<E>) => MiddlewareHandler<E>;
|
|
286
311
|
|
|
287
|
-
export { type Algorithm, type CloudflareRateLimitOptions, type HeadersFormat, MemoryStore, type QuotaUnit, type RateLimitBinding, type RateLimitInfo, type RateLimitOptions, type RateLimitStore, type RateLimitStoreAccess, type StoreResult, cloudflareRateLimiter, getClientIP, rateLimiter };
|
|
312
|
+
export { type Algorithm, type CloudflareRateLimitOptions, type HeadersFormat, MemoryStore, type QuotaUnit, type RateLimitBinding, type RateLimitInfo, type RateLimitOptions, type RateLimitStore, type RateLimitStoreAccess, type StoreResult, cloudflareRateLimiter, getClientIP, rateLimiter, shutdownDefaultStore };
|